Passed
Pull Request — master (#5310)
by Angel Fernando Quiroz
07:13
created

AbstractMigrationChamilo::addSettingCurrent()   A

Complexity

Conditions 5
Paths 2

Size

Total Lines 56
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 30
c 0
b 0
f 0
nc 2
nop 13
dl 0
loc 56
rs 9.1288

How to fix   Long Method    Many Parameters   

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:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
3
declare(strict_types=1);
4
5
/* For licensing terms, see /license.txt */
6
7
namespace Chamilo\CoreBundle\Migrations;
8
9
use Chamilo\CoreBundle\Entity\AbstractResource;
10
use Chamilo\CoreBundle\Entity\AccessUrl;
11
use Chamilo\CoreBundle\Entity\Admin;
12
use Chamilo\CoreBundle\Entity\Course;
13
use Chamilo\CoreBundle\Entity\ResourceInterface;
14
use Chamilo\CoreBundle\Entity\ResourceLink;
15
use Chamilo\CoreBundle\Entity\Session;
16
use Chamilo\CoreBundle\Entity\SettingsCurrent;
17
use Chamilo\CoreBundle\Entity\SettingsOptions;
18
use Chamilo\CoreBundle\Entity\User;
19
use Chamilo\CoreBundle\Repository\Node\UserRepository;
20
use Chamilo\CoreBundle\Repository\ResourceRepository;
21
use Chamilo\CoreBundle\Repository\SessionRepository;
22
use Chamilo\CourseBundle\Repository\CGroupRepository;
23
use DateTime;
24
use DateTimeZone;
25
use Doctrine\Migrations\AbstractMigration;
26
use Doctrine\ORM\EntityManagerInterface;
27
use Symfony\Component\DependencyInjection\ContainerInterface;
28
use Symfony\Component\Filesystem\Filesystem;
29
use Symfony\Component\HttpFoundation\File\UploadedFile;
30
31
abstract class AbstractMigrationChamilo extends AbstractMigration
32
{
33
    public const BATCH_SIZE = 20;
34
35
    protected ?EntityManagerInterface $entityManager = null;
36
    protected ?ContainerInterface $container = null;
37
38
    public function setEntityManager(EntityManagerInterface $entityManager): void
39
    {
40
        $this->entityManager = $entityManager;
41
    }
42
43
    public function setContainer(?ContainerInterface $container = null): void
44
    {
45
        $this->container = $container;
46
    }
47
48
    public function adminExist(): bool
49
    {
50
        $sql = 'SELECT user_id FROM admin WHERE user_id IN (SELECT id FROM user) ORDER BY id LIMIT 1';
51
        $result = $this->connection->executeQuery($sql);
52
        $adminRow = $result->fetchAssociative();
53
54
        if (empty($adminRow)) {
55
            return false;
56
        }
57
58
        return true;
59
    }
60
61
    public function getAdmin(): User
62
    {
63
        $admin = $this->entityManager
64
            ->getRepository(Admin::class)
0 ignored issues
show
Bug introduced by
The method getRepository() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

64
            ->/** @scrutinizer ignore-call */ getRepository(Admin::class)

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
65
            ->findOneBy([], ['id' => 'ASC'])
66
        ;
67
68
        return $admin->getUser();
69
    }
70
71
    /**
72
     * Speeds up SettingsCurrent creation.
73
     *
74
     * @param string $variable            The variable itself
75
     * @param string $subKey              The subkey
76
     * @param string $type                The type of setting (text, radio, select, etc)
77
     * @param string $category            The category (Platform, User, etc)
78
     * @param string $selectedValue       The default value
79
     * @param string $title               The setting title string name
80
     * @param string $comment             The setting comment string name
81
     * @param string $scope               The scope
82
     * @param string $subKeyText          Text if there is a subKey
83
     * @param int    $accessUrl           What URL it is for
84
     * @param bool   $accessUrlChangeable Whether it can be changed on each url
85
     * @param bool   $accessUrlLocked     Whether the setting for the current URL is
86
     *                                    locked to the current value
87
     * @param array  $options             Optional array in case of a radio-type field,
88
     *                                    to insert options
89
     */
90
    public function addSettingCurrent(
91
        $variable,
92
        $subKey,
93
        $type,
94
        $category,
95
        $selectedValue,
96
        $title,
97
        $comment,
98
        $scope = '',
99
        $subKeyText = '',
100
        $accessUrl = 1,
101
        $accessUrlChangeable = false,
102
        $accessUrlLocked = true,
103
        $options = []
104
    ): void {
105
        $accessUrl = $this->entityManager->find(AccessUrl::class, $accessUrl);
106
107
        $setting = new SettingsCurrent();
108
        $setting
109
            ->setVariable($variable)
110
            ->setSubkey($subKey)
111
            ->setType($type)
112
            ->setCategory($category)
113
            ->setSelectedValue($selectedValue)
114
            ->setTitle($title)
115
            ->setComment($comment)
116
            ->setScope($scope)
117
            ->setSubkeytext($subKeyText)
118
            ->setUrl($accessUrl)
119
            ->setAccessUrlChangeable((int) $accessUrlChangeable)
120
            ->setAccessUrlLocked((int) $accessUrlLocked)
121
        ;
122
123
        $this->entityManager->persist($setting);
124
125
        if (\count($options) > 0) {
126
            foreach ($options as $option) {
127
                if (empty($option['text'])) {
128
                    if ('true' === $option['value']) {
129
                        $option['text'] = 'Yes';
130
                    } else {
131
                        $option['text'] = 'No';
132
                    }
133
                }
134
135
                $settingOption = new SettingsOptions();
136
                $settingOption
137
                    ->setVariable($variable)
138
                    ->setValue($option['value'])
139
                    ->setDisplayText($option['text'])
140
                ;
141
142
                $this->entityManager->persist($settingOption);
143
            }
144
        }
145
        $this->entityManager->flush();
146
    }
147
148
    /**
149
     * @param string     $variable
150
     * @param null|mixed $configuration
151
     */
152
    public function getConfigurationValue($variable, $configuration = null)
153
    {
154
        global $_configuration;
155
156
        if (isset($configuration)) {
157
            $_configuration = $configuration;
158
        }
159
160
        if (isset($_configuration[$variable])) {
161
            return $_configuration[$variable];
162
        }
163
164
        return false;
165
    }
166
167
    /**
168
     * Remove a setting completely.
169
     *
170
     * @param string $variable The setting variable name
171
     */
172
    public function removeSettingCurrent($variable): void
173
    {
174
        // to be implemented
175
    }
176
177
    public function addLegacyFileToResource(
178
        string $filePath,
179
        ResourceRepository $repo,
180
        AbstractResource $resource,
181
        $id,
182
        $fileName = '',
183
        $description = ''
184
    ): bool {
185
        $class = $resource::class;
186
        $documentPath = basename($filePath);
187
188
        if (is_dir($filePath) || (!is_dir($filePath) && !file_exists($filePath))) {
189
            $this->warnIf(true, "Cannot migrate {$class} #'.{$id}.' file not found: {$documentPath}");
190
191
            return false;
192
        }
193
194
        $mimeType = mime_content_type($filePath);
195
        if (empty($fileName)) {
196
            $fileName = basename($documentPath);
197
        }
198
        $file = new UploadedFile($filePath, $fileName, $mimeType, null, true);
199
        $repo->addFile($resource, $file);
200
201
        return true;
202
    }
203
204
    public function fixItemProperty(
205
        $tool,
206
        ResourceRepository $repo,
207
        $course,
208
        $admin,
209
        ResourceInterface $resource,
210
        $parentResource,
211
        array $items = []
212
    ) {
213
        $courseId = $course->getId();
214
        $id = $resource->getResourceIdentifier();
215
216
        if (empty($items)) {
217
            $sql = "SELECT * FROM c_item_property
218
                    WHERE tool = '{$tool}' AND c_id = {$courseId} AND ref = {$id}";
219
            $result = $this->connection->executeQuery($sql);
220
            $items = $result->fetchAllAssociative();
221
        }
222
223
        // For some reason the resource doesn't have a c_item_property value.
224
        if (empty($items)) {
225
            return false;
226
        }
227
228
        $sessionRepo = $this->container->get(SessionRepository::class);
0 ignored issues
show
Bug introduced by
The method get() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

228
        /** @scrutinizer ignore-call */ 
229
        $sessionRepo = $this->container->get(SessionRepository::class);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
229
        $groupRepo = $this->container->get(CGroupRepository::class);
230
        $userRepo = $this->container->get(UserRepository::class);
231
232
        $resource->setParent($parentResource);
0 ignored issues
show
Bug introduced by
The method setParent() does not exist on Chamilo\CoreBundle\Entity\ResourceInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to Chamilo\CoreBundle\Entity\ResourceInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

232
        $resource->/** @scrutinizer ignore-call */ 
233
                   setParent($parentResource);
Loading history...
233
        $resourceNode = null;
234
        $userList = [];
235
        $groupList = [];
236
        $sessionList = [];
237
        foreach ($items as $item) {
238
            $visibility = (int) $item['visibility'];
239
            $userId = (int) $item['insert_user_id'];
240
            $sessionId = $item['session_id'] ?? 0;
241
            $groupId = $item['to_group_id'] ?? 0;
242
            if (empty($item['lastedit_date'])) {
243
                $lastUpdatedAt = new DateTime('now', new DateTimeZone('UTC'));
244
            } else {
245
                $lastUpdatedAt = new DateTime($item['lastedit_date'], new DateTimeZone('UTC'));
246
            }
247
            $newVisibility = ResourceLink::VISIBILITY_DRAFT;
248
249
            // Old 1.11.x visibility (item property) is based in this switch:
250
            switch ($visibility) {
251
                case 0:
252
                    $newVisibility = ResourceLink::VISIBILITY_DRAFT;
253
254
                    break;
255
256
                case 1:
257
                    $newVisibility = ResourceLink::VISIBILITY_PUBLISHED;
258
259
                    break;
260
            }
261
262
            // If c_item_property.insert_user_id doesn't exist we use the first admin id.
263
            $user = null;
264
            if (isset($userList[$userId])) {
265
                $user = $userList[$userId];
266
            } else {
267
                if (!empty($userId)) {
268
                    $userFound = $userRepo->find($userId);
269
                    if ($userFound) {
270
                        $user = $userList[$userId] = $userRepo->find($userId);
271
                    }
272
                }
273
            }
274
275
            if (null === $user) {
276
                $user = $admin;
277
            }
278
279
            $session = null;
280
            if (!empty($sessionId)) {
281
                if (isset($sessionList[$sessionId])) {
282
                    $session = $sessionList[$sessionId];
283
                } else {
284
                    $session = $sessionList[$sessionId] = $sessionRepo->find($sessionId);
285
                }
286
            }
287
288
            $group = null;
289
            if (!empty($groupId)) {
290
                if (isset($groupList[$groupId])) {
291
                    $group = $groupList[$groupId];
292
                } else {
293
                    $group = $groupList[$groupId] = $groupRepo->find($groupId);
294
                }
295
            }
296
297
            if (null === $resourceNode) {
298
                $resourceNode = $repo->addResourceNode($resource, $user, $parentResource);
299
                $this->entityManager->persist($resourceNode);
300
            }
301
            $resource->addCourseLink($course, $session, $group, $newVisibility);
0 ignored issues
show
Bug introduced by
The method addCourseLink() does not exist on Chamilo\CoreBundle\Entity\ResourceInterface. It seems like you code against a sub-type of said class. However, the method does not exist in Chamilo\CoreBundle\Entity\User. Are you sure you never get one of those? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

301
            $resource->/** @scrutinizer ignore-call */ 
302
                       addCourseLink($course, $session, $group, $newVisibility);
Loading history...
302
303
            if (2 === $visibility) {
304
                $link = $resource->getResourceNode()->getResourceLinkByContext($course, $session, $group);
305
                $link->setDeletedAt($lastUpdatedAt);
306
            }
307
308
            $this->entityManager->persist($resource);
309
        }
310
311
        return true;
312
    }
313
314
    public function fileExists($filePath): bool
315
    {
316
        return file_exists($filePath) && !is_dir($filePath) && is_readable($filePath);
317
    }
318
319
    public function findCourse(int $id): ?Course
320
    {
321
        if (0 === $id) {
322
            return null;
323
        }
324
325
        return $this->entityManager->find(Course::class, $id);
326
    }
327
328
    public function findSession(int $id): ?Session
329
    {
330
        if (0 === $id) {
331
            return null;
332
        }
333
334
        return $this->entityManager->find(Session::class, $id);
335
    }
336
337
    private function generateFilePath(string $filename): string
338
    {
339
        $cacheDir = $this->container->get('kernel')->getCacheDir();
340
341
        return $cacheDir.'/migration_'.$filename;
342
    }
343
344
    protected function writeFile(string $filename, string $content): void
345
    {
346
        $fullFilename = $this->generateFilePath($filename);
347
348
        $fs = new Filesystem();
349
        $fs->dumpFile($fullFilename, $content);
350
    }
351
352
    protected function readFile(string $filename): string
353
    {
354
        $fullFilename = $this->generateFilePath($filename);
355
356
        return file_get_contents($fullFilename);
357
    }
358
359
    protected function removeFile(string $filename): void
360
    {
361
        $fullFilename = $this->generateFilePath($filename);
362
363
        $fs = new Filesystem();
364
        $fs->remove($fullFilename);
365
    }
366
}
367