Version20201212203625::up()   F
last analyzed

Complexity

Conditions 22
Paths 1134

Size

Total Lines 241
Code Lines 141

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 22
eloc 141
nc 1134
nop 1
dl 0
loc 241
rs 0
c 0
b 0
f 0

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
/* For licensing terms, see /license.txt */
6
7
namespace Chamilo\CoreBundle\Migrations\Schema\V200;
8
9
use Chamilo\CoreBundle\Entity\Asset;
10
use Chamilo\CoreBundle\Entity\AttemptFeedback;
11
use Chamilo\CoreBundle\Entity\AttemptFile;
12
use Chamilo\CoreBundle\Entity\Course;
13
use Chamilo\CoreBundle\Entity\TrackEAttempt;
14
use Chamilo\CoreBundle\Migrations\AbstractMigrationChamilo;
15
use Chamilo\CoreBundle\Repository\Node\CourseRepository;
16
use Chamilo\CourseBundle\Entity\CDocument;
17
use Chamilo\CourseBundle\Repository\CDocumentRepository;
18
use Chamilo\Kernel;
19
use Doctrine\DBAL\Connection;
20
use Doctrine\DBAL\Schema\Schema;
21
use Doctrine\ORM\EntityManager;
22
use Symfony\Component\HttpFoundation\File\UploadedFile;
23
24
final class Version20201212203625 extends AbstractMigrationChamilo
25
{
26
    public function getDescription(): string
27
    {
28
        return 'Migrate c_document';
29
    }
30
31
    public function up(Schema $schema): void
32
    {
33
        $container = $this->getContainer();
34
        $doctrine = $container->get('doctrine');
35
36
        /** @var EntityManager $em */
37
        $em = $doctrine->getManager();
38
39
        /** @var Connection $connection */
40
        $connection = $em->getConnection();
41
42
        /** @var CDocumentRepository $documentRepo */
43
        $documentRepo = $container->get(CDocumentRepository::class);
44
        $courseRepo = $container->get(CourseRepository::class);
45
        $attemptRepo = $em->getRepository(TrackEAttempt::class);
46
47
        /** @var Kernel $kernel */
48
        $kernel = $container->get('kernel');
49
        $rootPath = $kernel->getProjectDir();
50
51
        $batchSize = self::BATCH_SIZE;
52
53
        // Migrate teacher exercise audio.
54
        $q = $em->createQuery('SELECT c FROM Chamilo\CoreBundle\Entity\Course c');
55
56
        /** @var Course $course */
57
        foreach ($q->toIterable() as $course) {
58
            $courseId = $course->getId();
59
            $sql = "SELECT iid, path
60
                    FROM c_document
61
                    WHERE
62
                          c_id = $courseId AND
63
                          path LIKE '/../exercises/teacher_audio%'
64
                    ";
65
            $result = $connection->executeQuery($sql);
66
            $documents = $result->fetchAllAssociative();
67
68
            foreach ($documents as $documentData) {
69
                $documentId = $documentData['iid'];
70
                $path = $documentData['path'];
71
72
                $path = str_replace('//', '/', $path);
73
                $path = str_replace('/../exercises/teacher_audio/', '', $path);
74
75
                $filePath = $rootPath.'/app/courses/'.$course->getDirectory().'/exercises/teacher_audio/'.$path;
76
                error_log('MIGRATIONS :: $filePath -- '.$filePath.' ...');
77
                if ($this->fileExists($filePath)) {
78
                    preg_match('#/(.*)/#', '/'.$path, $matches);
79
                    if (isset($matches[1]) && !empty($matches[1])) {
80
                        $attemptId = $matches[1];
81
82
                        /** @var TrackEAttempt $attempt */
83
                        $attempt = $attemptRepo->find($attemptId);
84
                        if (null !== $attempt) {
85
                            if ($attempt->getAttemptFeedbacks()->count() > 0) {
86
                                continue;
87
                            }
88
89
                            $fileName = basename($filePath);
90
                            $mimeType = mime_content_type($filePath);
91
                            $file = new UploadedFile($filePath, $fileName, $mimeType, null, true);
92
                            $asset = (new Asset())
93
                                ->setCategory(Asset::EXERCISE_FEEDBACK)
94
                                ->setTitle($fileName)
95
                                ->setFile($file)
96
                            ;
97
                            $em->persist($asset);
98
                            $em->flush();
99
100
                            $attempFeedback = (new AttemptFeedback())
101
                                ->setAsset($asset)
102
                            ;
103
                            $attempt->addAttemptFeedback($attempFeedback);
104
                            $em->persist($attempFeedback);
105
                            $em->flush();
106
107
                            /*$sql = "UPDATE c_document
108
                                    SET comment = 'skip_migrate'
109
                                    WHERE iid = $documentId
110
                            ";
111
                            $connection->executeQuery($sql);*/
112
                        }
113
                    }
114
                }
115
            }
116
            $em->flush();
117
            $em->clear();
118
        }
119
120
        $em->flush();
121
        $em->clear();
122
123
        // Migrate student exercise audio
124
        $q = $em->createQuery('SELECT c FROM Chamilo\CoreBundle\Entity\Course c');
125
126
        /** @var Course $course */
127
        foreach ($q->toIterable() as $course) {
128
            $courseId = $course->getId();
129
130
            $sql = "SELECT iid, path
131
                    FROM c_document
132
                    WHERE
133
                          c_id = $courseId AND
134
                          path NOT LIKE '/../exercises/teacher_audio%' AND
135
                          path LIKE '/../exercises/%'
136
                    ";
137
            $result = $connection->executeQuery($sql);
138
            $documents = $result->fetchAllAssociative();
139
140
            foreach ($documents as $documentData) {
141
                $documentId = $documentData['iid'];
142
                $path = $documentData['path'];
143
144
                $path = str_replace('//', '/', $path);
145
                $path = str_replace('/../exercises/', '', $path);
146
147
                $filePath = $rootPath.'/app/courses/'.$course->getDirectory().'/exercises/'.$path;
148
                error_log('MIGRATIONS :: $filePath -- '.$filePath.' ...');
149
                if ($this->fileExists($filePath)) {
150
                    $fileName = basename($filePath);
151
                    preg_match('#/(.*)/(.*)/(.*)/(.*)/#', '/'.$path, $matches);
152
                    $sessionId = $matches[1] ?? 0;
153
                    $exerciseId = $matches[2] ?? 0;
154
                    $questionId = $matches[3] ?? 0;
155
                    $userId = $matches[4] ?? 0;
156
157
                    /** @var TrackEAttempt $attempt */
158
                    $attempt = $attemptRepo->findOneBy([
159
                        'user' => $userId,
160
                        'questionId' => $questionId,
161
                        'filename' => $fileName,
162
                    ]);
163
                    if (null !== $attempt) {
164
                        if ($attempt->getAttemptFiles()->count() > 0) {
165
                            continue;
166
                        }
167
168
                        $mimeType = mime_content_type($filePath);
169
                        $file = new UploadedFile($filePath, $fileName, $mimeType, null, true);
170
                        $asset = (new Asset())
171
                            ->setCategory(Asset::EXERCISE_ATTEMPT)
172
                            ->setTitle($fileName)
173
                            ->setFile($file)
174
                        ;
175
                        $em->persist($asset);
176
                        $em->flush();
177
178
                        $attemptFile = (new AttemptFile())
179
                            ->setAsset($asset)
180
                        ;
181
                        $attempt->addAttemptFile($attemptFile);
182
                        $em->persist($attemptFile);
183
                        $em->flush();
184
185
                        /*$sql = "UPDATE c_document
186
                                SET comment = 'skip_migrate'
187
                                WHERE iid = $documentId
188
                        ";
189
                        $connection->executeQuery($sql);*/
190
                    }
191
                }
192
            }
193
            $em->flush();
194
            $em->clear();
195
        }
196
197
        $em->flush();
198
        $em->clear();
199
200
        // Migrate normal documents.
201
        $q = $em->createQuery('SELECT c FROM Chamilo\CoreBundle\Entity\Course c');
202
203
        /** @var Course $course */
204
        foreach ($q->toIterable() as $course) {
205
            $counter = 1;
206
            $courseId = $course->getId();
207
208
            $sql = "SELECT iid, path FROM c_document
209
                    WHERE
210
                          c_id = {$courseId} AND
211
                          path NOT LIKE '/../exercises/%' AND
212
                          path NOT LIKE '/chat_files/%'
213
                    ORDER BY filetype DESC, path";
214
            $result = $connection->executeQuery($sql);
215
            $documents = $result->fetchAllAssociative();
216
            foreach ($documents as $documentData) {
217
                $documentId = $documentData['iid'];
218
                $documentPath = $documentData['path'];
219
                $course = $courseRepo->find($courseId);
220
221
                /** @var CDocument $document */
222
                $document = $documentRepo->find($documentId);
223
                if ($document->hasResourceNode()) {
224
                    continue;
225
                }
226
227
                $parent = null;
228
                if ('.' !== \dirname($documentPath)) {
229
                    $currentPath = \dirname($documentPath);
230
                    $sql = "SELECT iid FROM c_document
231
                    WHERE
232
                          c_id = {$courseId} AND
233
                          path LIKE '$currentPath'";
234
                    $result = $connection->executeQuery($sql);
235
                    $parentId = $result->fetchOne();
236
237
                    if (!empty($parentId)) {
238
                        $parent = $documentRepo->find($parentId);
239
                    }
240
                }
241
242
                if (null === $parent) {
243
                    $parent = $course;
244
                }
245
                if (null === $parent->getResourceNode()) {
246
                    continue;
247
                }
248
                $admin = $this->getAdmin();
249
                $result = $this->fixItemProperty('document', $documentRepo, $course, $admin, $document, $parent);
250
251
                if (false === $result) {
252
                    continue;
253
                }
254
                $documentPath = ltrim($documentPath, '/');
255
                $filePath = $rootPath.'/app/courses/'.$course->getDirectory().'/document/'.$documentPath;
256
                error_log('MIGRATIONS :: $filePath -- '.$filePath.' ...');
257
                $this->addLegacyFileToResource($filePath, $documentRepo, $document, $documentId);
258
                $em->persist($document);
259
260
                if (($counter % $batchSize) === 0) {
261
                    $em->flush();
262
                    $em->clear();
263
                }
264
                $counter++;
265
            }
266
            $em->flush();
267
            $em->clear();
268
        }
269
270
        $em->flush();
271
        $em->clear();
272
    }
273
274
    public function down(Schema $schema): void {}
275
}
276