Completed
Push — master ( 802ebe...107004 )
by Craig
07:08
created

FileIOHelper::importUsersFromFile()   C

Complexity

Conditions 14
Paths 40

Size

Total Lines 72
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
eloc 39
c 0
b 0
f 0
nc 40
nop 2
dl 0
loc 72
rs 6.2666

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
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Zikula package.
7
 *
8
 * Copyright Zikula Foundation - https://ziku.la/
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Zikula\ZAuthModule\Helper;
15
16
use Symfony\Component\HttpFoundation\File\File;
17
use Symfony\Contracts\Translation\TranslatorInterface;
18
use Zikula\Bundle\CoreBundle\Translation\TranslatorTrait;
19
use Zikula\ZAuthModule\Api\ApiInterface\UserCreationApiInterface;
20
21
class FileIOHelper
22
{
23
    use TranslatorTrait;
24
25
    /**
26
     * @var MailHelper
27
     */
28
    private $mailHelper;
29
30
    /**
31
     * @var UserCreationApiInterface
32
     */
33
    private $userCreationApi;
34
35
    /**
36
     * @var array
37
     */
38
    private $createdUsers;
39
40
    public function __construct(
41
        TranslatorInterface $translator,
42
        UserCreationApiInterface $userCreationApi,
43
        MailHelper $mailHelper
44
    ) {
45
        $this->setTranslator($translator);
46
        $this->userCreationApi = $userCreationApi;
47
        $this->mailHelper = $mailHelper;
48
    }
49
50
    public function importUsersFromFile(File $file, string $delimiter = ','): string
51
    {
52
        // read the file
53
        if (!$lines = file($file->getPathname())) {
54
            return $this->trans('Error! It has not been possible to read the import file.');
55
        }
56
        $expectedFields = ['uname', 'pass', 'email', 'activated', 'sendmail', 'groups'];
57
        $firstLineArray = explode($delimiter, str_replace('"', '', trim($lines[0])));
58
        foreach ($firstLineArray as $field) {
59
            if (!in_array(mb_strtolower(trim($field)), $expectedFields, true)) {
60
                return $this->trans('Error! The import file does not have the expected field %s in the first row. Please check your import file.', ['%s' => $field]);
61
            }
62
        }
63
        unset($lines[0]);
64
65
        $counter = 1;
66
        $importValues = [];
67
68
        // prepare the array for import
69
        foreach ($lines as $line) {
70
            $line = str_replace('"', '', trim($line));
71
            $lineArray = explode($delimiter, $line);
72
73
            // check if the line has all the needed values
74
            if (count($lineArray) !== count($firstLineArray)) {
75
                return $this->trans('Error! The number of parameters in line %s is not correct. Please check your import file.', ['%s' => $counter]);
76
            }
77
            $importValues[] = array_combine($firstLineArray, $lineArray);
78
            $counter++;
79
        }
80
81
        if (empty($importValues)) {
82
            return $this->trans('Error! The import file does not have values.');
83
        }
84
        $generateErrorList = function ($errors) {
85
            $errorList = '';
86
            foreach ($errors as $error) {
87
                $errorList .= $error->getMessage() . PHP_EOL;
88
            }
89
90
            return $errorList;
91
        };
92
93
        // validate values and return errors if found
94
        if (true !== $errors = $this->userCreationApi->isValidUserDataArray($importValues)) {
95
            return $generateErrorList($errors);
96
        }
97
98
        // create users
99
        if ($errors = $this->userCreationApi->createUsers($importValues)) {
100
            if (0 !== count($errors)) {
101
                return $generateErrorList($errors);
102
            }
103
        }
104
105
        // finally, persist all the created users
106
        $this->userCreationApi->persist();
107
        $this->createdUsers = $this->userCreationApi->getCreatedUsers();
108
109
        // send email if indicated
110
        foreach ($importValues as $importValue) {
111
            $activated = $importValue['activated'] ?? 1;
112
            $sendmail = $importValue['sendmail'] ?? 1;
113
            if ($activated && $sendmail) {
114
                $templateArgs = [
115
                    'user' => $importValue
116
                ];
117
                $this->mailHelper->sendNotification($importValue['email'], 'importnotify', $templateArgs);
118
            }
119
        }
120
121
        return '';
122
    }
123
124
    /**
125
     * @return \Zikula\UsersModule\Entity\UserEntity[]
126
     */
127
    public function getCreatedUsers(): array
128
    {
129
        return $this->createdUsers;
130
    }
131
}
132