Completed
Push — add-pleio-mod ( 6d68a5 )
by
unknown
28:07
created

Import::run()   D

Complexity

Conditions 16
Paths 66

Size

Total Lines 84
Code Lines 51

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 272

Importance

Changes 0
Metric Value
cc 16
eloc 51
nc 66
nop 3
dl 0
loc 84
rs 4.8736
c 0
b 0
f 0
ccs 0
cts 67
cp 0
crap 272

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
namespace ModPleio;
3
4
class Import {
5
    public static function run($csv_location, $columns, \ElggUser $initiator) {
6
        global $CONFIG;
7
8
        $site = elgg_get_site_entity();
9
        $profile_fields = get_config("profile_fields");
10
11
        $fh = fopen($csv_location, "r");
12
        if (!$fh) {
13
            throw new Exception("Invalid import file");
14
        }
15
16
        $stats = [
17
            "created" => 0,
18
            "updated" => 0,
19
            "error" => 0
20
        ];
21
22
        $skip_first_line = true;
23
        while (($data = fgetcsv($fh, 0, ";")) !== false) {
24
            if ($skip_first_line) {
25
                $skip_first_line = false;
26
                continue;
27
            }
28
29
            $data = Import::extractData($columns, $data);
30
31
            $user = Import::getUserByAttributes($data);
32
            if (!$user) {
33
                $user = Import::registerUser($data);
34
                if ($user) {
35
                    $stats["created"] += 1;
36
                } else {
37
                    $stats["error"] += 1;
38
                }
39
            } else {
40
                $stats["updated"] += 1;
41
            }
42
43
            if (!$user) {
44
                continue;
45
            }
46
47
            if ($data["email"] && $user->email !== $data["email"]) {
48
                $user->email = $data["email"];
49
            }
50
51
            if ($data["name"] && $user->name !== $data["name"]) {
52
                $user->name = $data["name"];
53
            }
54
55
            foreach ($columns as $id => $metadata_name) {
56
                $value = $data[$metadata_name];
57
                if (empty($value)) {
58
                    continue;
59
                }
60
61
                if (!array_key_exists($metadata_name, $profile_fields)) {
62
                    continue;
63
                }
64
65
                $field_type = $profile_fields[$metadata_name];
66
67
                if ($profile_fields[$metadata_name] == "tags") {
68
                    elgg_delete_metadata([
69
                        "guid" => $user->guid,
70
                        "metadata_name" => $metadata_name,
71
                        "limit" => 0
72
                    ]);
73
74
                    foreach (string_to_tag_array($value) as $v) {
75
                        create_metadata($user->guid, $metadata_name, $v, "", $user->guid, get_default_access(), true, $site->guid);
0 ignored issues
show
Unused Code introduced by
The call to create_metadata() has too many arguments starting with $site->guid.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
76
                    }
77
                } else {
78
                    create_metadata($user->guid, $metadata_name, $value, "", $user->guid, get_default_access(), false, $site->guid);
0 ignored issues
show
Unused Code introduced by
The call to create_metadata() has too many arguments starting with $site->guid.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
79
                }
80
            }
81
82
            $user->save();
83
        }
84
85
        unlink($csv_location);
86
87
        return $stats;
88
    }
89
90
    public function extractData($columns, $data) {
91
        $result = [];
92
        foreach ($columns as $id => $metadata_name) {
93
            if (!$metadata_name) {
94
                continue;
95
            }
96
97
            $result[$metadata_name] = $data[$id];
98
        }
99
100
        return $result;
101
    }
102
103
    public function registerUser($data) {
104
        if (!$data["name"] || !$data["email"]) {
105
            return false;
106
        }
107
108
        $user = false;
109
110
        try {
111
            $username = Import::generateUniqueUsername($data);
112
            $password = generate_random_cleartext_password();
113
            $guid = register_user($username, $password, $data["name"], $data["email"]);
114
            elgg_set_user_validation_status($guid, true, "email");
0 ignored issues
show
Bug introduced by
It seems like $guid defined by register_user($username,...name'], $data['email']) on line 113 can also be of type false or null; however, elgg_set_user_validation_status() does only seem to accept integer, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
115
            $user = get_entity($guid);
0 ignored issues
show
Bug introduced by
It seems like $guid defined by register_user($username,...name'], $data['email']) on line 113 can also be of type false or null; however, get_entity() does only seem to accept integer, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
116
        } catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The class ModPleio\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
117
            elgg_log("Could not register user " . $e->getMessage(), "ERROR");
118
        }
119
120
        return $user;
121
    }
122
123
    public function generateUniqueUsername($data) {
124
        $email = $data["email"];
125
        list($name, $email) = explode("@", $email);
0 ignored issues
show
Unused Code introduced by
The assignment to $email is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
126
        $name = preg_replace("/[^a-zA-Z0-9\.]+/", "", trim($name));
127
128
        while (strlen($name) < 4) {
129
            $name .= "0";
130
        }
131
132
        $hidden = access_show_hidden_entities(true);
133
134 View Code Duplication
        if (get_user_by_username($name)) {
135
            $i = 1;
136
137
            while (get_user_by_username($name . $i)) {
138
                $i++;
139
            }
140
141
            $result = $name . $i;
142
        } else {
143
            $result = $name;
144
        }
145
146
        access_show_hidden_entities($hidden);
147
148
        return $result;
149
    }
150
151
    public function getUserByAttributes($data) {
152
        $user = false;
153
154
        if ($data["guid"]) {
155
            $user = get_entity($data["guid"]);
156
        } elseif ($data["username"]) {
157
            $user = get_user_by_username($data["username"]);
158
        } elseif ($data["email"]) {
159
            $users = get_user_by_email($data["email"]);
160
            $user = $users[0];
161
        }
162
163
        return $user;
164
    }
165
}