UserImportModel   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 0
dl 0
loc 72
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
B importData() 0 42 7
A findAvatar() 0 16 3
1
<?php namespace VojtaSvoboda\UserImportExport\Models;
2
3
use Backend\Models\ImportModel;
4
use System\Classes\MediaLibrary;
5
use System\Models\File;
6
use RainLab\Location\Models\State;
7
use RainLab\User\Models\User;
8
9
class UserImportModel extends ImportModel
10
{
11
    public $rules = [];
12
13
    public $imageStoragePath = '/users';
14
15
    public $imagePublic = true;
16
17
    public function importData($results, $sessionKey = null)
18
    {
19
        foreach ($results as $row => $data) {
20
            $data += [
21
                'is_activated' => true,
22
            ];
23
24
            if (empty($data['username'])) {
25
                $data['username'] = $data['email'];
26
            }
27
28
            if (empty($data['password'])) {
29
                $data['password'] = $data['username'];
30
            }
31
32
            if (empty($data['password_confirmation'])) {
33
                $data['password_confirmation'] = $data['password'];
34
            }
35
36
            try {
37
                $user = new User();
38
                $user->fill($data);
39
40
                // try to find avatar
41
                $avatar = $this->findAvatar($data['username']);
42
                if ($avatar) {
43
                    $user->avatar = $avatar;
44
                }
45
46
                // save user
47
                $user->save();
48
49
                // activate user (it sends welcome email)
50
                // $user->attemptActivation($user->activation_code);
51
52
                $this->logCreated();
53
54
            } catch (\Exception $ex) {
55
                $this->logError($row, $ex->getMessage());
56
            }
57
        }
58
    }
59
60
    /**
61
     * @param string $username
62
     * @return string|null
63
     */
64
    private function findAvatar($username)
65
    {
66
        $library = MediaLibrary::instance();
67
        $files = $library->listFolderContents($this->imageStoragePath, 'title', 'image');
68
69
        foreach ($files as $file) {
70
            $pathinfo = pathinfo($file->publicUrl);
71
            if ($pathinfo['filename'] == $username) {
72
                $newFile = new File();
73
                $newFile->is_public = $this->imagePublic;
74
                $newFile->fromFile(storage_path('app/media' . $file->path));
75
76
                return $newFile;
77
            }
78
        }
79
    }
80
}
81