Version20201212203625   A
last analyzed

Complexity

Total Complexity 24

Size/Duplication

Total Lines 240
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 139
dl 0
loc 240
rs 10
c 0
b 0
f 0
wmc 24

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getDescription() 0 3 1
A down() 0 1 1
F up() 0 230 22
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 Doctrine\DBAL\Schema\Schema;
19
use Symfony\Component\HttpFoundation\File\UploadedFile;
20
21
final class Version20201212203625 extends AbstractMigrationChamilo
22
{
23
    public function getDescription(): string
24
    {
25
        return 'Migrate c_document';
26
    }
27
28
    public function up(Schema $schema): void
29
    {
30
        $documentRepo = $this->container->get(CDocumentRepository::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

30
        /** @scrutinizer ignore-call */ 
31
        $documentRepo = $this->container->get(CDocumentRepository::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...
31
        $courseRepo = $this->container->get(CourseRepository::class);
32
        $attemptRepo = $this->entityManager->getRepository(TrackEAttempt::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

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