LDAPGroupSyncTask   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 117
Duplicated Lines 27.35 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 7
dl 32
loc 117
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getTitle() 0 4 1
C run() 32 90 10
A log() 0 5 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 LDAPGroupSyncTask
4
 *
5
 * A task to sync all groups to the site using LDAP.
6
 */
7
class LDAPGroupSyncTask extends BuildTask
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
    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...
10
        'ldapService' => '%$LDAPService'
11
    ];
12
13
    /**
14
     * Setting this to true causes the sync to delete any local Group
15
     * records that were previously imported, but no longer existing in LDAP.
16
     *
17
     * @config
18
     * @var bool
19
     */
20
    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...
21
22
    public function getTitle()
23
    {
24
        return _t('LDAPGroupSyncJob.SYNCTITLE', 'Sync all groups from Active Directory');
25
    }
26
27
    public function run($request)
28
    {
29
        // get all groups from LDAP, but only get the attributes we need.
30
        // this is useful to avoid holding onto too much data in memory
31
        // especially in the case where getGroups() would return a lot of groups
32
        $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...
33
            false,
34
            ['objectguid', 'samaccountname', 'dn', 'name', 'description'],
35
            // Change the indexing attribute so we can look up by GUID during the deletion process below.
36
            'objectguid'
37
        );
38
39
        $start = time();
40
41
        $created = 0;
42
        $updated = 0;
43
        $deleted = 0;
44
45 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...
46
            $group = Group::get()->filter('GUID', $data['objectguid'])->limit(1)->first();
47
48
            if (!($group && $group->exists())) {
49
                // create the initial Group with some internal fields
50
                $group = new Group();
51
                $group->GUID = $data['objectguid'];
52
53
                $this->log(sprintf(
54
                    'Creating new Group (GUID: %s, sAMAccountName: %s)',
55
                    $data['objectguid'],
56
                    $data['samaccountname']
57
                ));
58
                $created++;
59
            } else {
60
                $this->log(sprintf(
61
                    'Updating existing Group "%s" (ID: %s, GUID: %s, sAMAccountName: %s)',
62
                    $group->getTitle(),
63
                    $group->ID,
64
                    $data['objectguid'],
65
                    $data['samaccountname']
66
                ));
67
                $updated++;
68
            }
69
70
            try {
71
                $this->ldapService->updateGroupFromLDAP($group, $data);
72
            } catch (Exception $e) {
73
                $this->log($e->getMessage());
74
                continue;
75
            }
76
        }
77
78
        // remove Group records that were previously imported, but no longer exist in the directory
79
        // NOTE: DB::query() here is used for performance and so we don't run out of memory
80
        if ($this->config()->destructive) {
81
            foreach (DB::query('SELECT "ID", "GUID" FROM "Group" WHERE "GUID" IS NOT NULL') as $record) {
82
                if (!isset($ldapGroups[$record['GUID']])) {
83
                    $group = Group::get()->byId($record['ID']);
84
85
                    $this->log(sprintf(
86
                        'Removing Group "%s" (GUID: %s) that no longer exists in LDAP.',
87
                        $group->Title,
88
                        $group->GUID
89
                    ));
90
91
                    try {
92
                        // Cascade into mappings, just to clean up behind ourselves.
93
                        foreach ($group->LDAPGroupMappings() as $mapping) {
94
                            $mapping->delete();
95
                        }
96
                        $group->delete();
97
                    } catch (Exception $e) {
98
                        $this->log($e->getMessage());
99
                        continue;
100
                    }
101
102
                    $deleted++;
103
                }
104
            }
105
        }
106
107
        $end = time() - $start;
108
109
        $this->log(sprintf(
110
            'Done. Created %s records. Updated %s records. Deleted %s records. Duration: %s seconds',
111
            $created,
112
            $updated,
113
            $deleted,
114
            round($end, 0)
115
        ));
116
    }
117
118
    protected function log($message)
119
    {
120
        $message = sprintf('[%s] ', date('Y-m-d H:i:s')) . $message;
121
        echo Director::is_cli() ? ($message . PHP_EOL) : ($message . '<br>');
122
    }
123
}
124