Passed
Pull Request — master (#6259)
by
unknown
09:02
created

Version20250429144100::up()   B

Complexity

Conditions 7
Paths 3

Size

Total Lines 80
Code Lines 52

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 52
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 80
rs 8.1138

How to fix   Long Method   

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\Repository\AssetRepository;
11
use Chamilo\CourseBundle\Entity\CLp;
12
use Chamilo\CoreBundle\Migrations\AbstractMigrationChamilo;
13
use Chamilo\CourseBundle\Repository\CLpRepository;
14
use Doctrine\DBAL\Schema\Schema;
15
use Symfony\Component\HttpFoundation\File\UploadedFile;
16
17
final class Version20250429144100 extends AbstractMigrationChamilo
18
{
19
    public function getDescription(): string
20
    {
21
        return 'Migrate SCORM packages into asset system.';
22
    }
23
24
    public function up(Schema $schema): void
25
    {
26
        $this->log('Starting SCORM migration...');
27
28
        $assetRepo = $this->container->get( AssetRepository::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

28
        /** @scrutinizer ignore-call */ 
29
        $assetRepo = $this->container->get( AssetRepository::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...
29
        $lpRepo = $this->container->get(CLpRepository::class);;
30
31
        $courses = $this->entityManager->createQuery('SELECT c FROM Chamilo\CoreBundle\Entity\Course c')->toIterable();
0 ignored issues
show
Bug introduced by
The method createQuery() 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

31
        $courses = $this->entityManager->/** @scrutinizer ignore-call */ createQuery('SELECT c FROM Chamilo\CoreBundle\Entity\Course c')->toIterable();

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...
32
33
        foreach ($courses as $course) {
34
            $courseId = $course->getId();
35
            $courseDir = $course->getDirectory();
36
            $this->log("Processing course ID: $courseId - Directory: $courseDir");
37
38
            $scorms = $lpRepo->createQueryBuilder('lp')
39
                ->join('lp.resourceNode', 'rn')
40
                ->join('rn.resourceLinks', 'rl')
41
                ->where('lp.lpType = :type')
42
                ->andWhere('rl.course = :course')
43
                ->setParameter('type', CLp::SCORM_TYPE)
44
                ->setParameter('course', $course)
45
                ->getQuery()
46
                ->getResult();
47
48
            if (empty($scorms)) {
49
                $this->log("No SCORMs found for course $courseDir");
50
                continue;
51
            }
52
53
            foreach ($scorms as $lp) {
54
                $lpId = $lp->getIid();
55
                $path = rtrim($lp->getPath(), '/.');
56
57
                $this->log("Processing SCORM LP id=$lpId path=$path");
58
59
                $folderPath = $this->getUpdateRootPath()."/app/courses/$courseDir/scorm/$path";
60
61
                if (!is_dir($folderPath)) {
62
                    $this->log("SCORM folder not found: $folderPath");
63
                    continue;
64
                }
65
66
                $zipName = basename($path).'.zip';
67
                $tmpZipPath = "/tmp/$zipName";
68
69
                if (!file_exists($tmpZipPath)) {
70
                    $this->log("Zipping SCORM folder: $folderPath -> $tmpZipPath");
71
                    $this->zipFolder($folderPath, $tmpZipPath);
72
                }
73
74
                if (!file_exists($tmpZipPath)) {
75
                    $this->log("Failed to create zip: $tmpZipPath");
76
                    continue;
77
                }
78
79
                $file = new UploadedFile($tmpZipPath, $zipName, 'application/zip', null, true);
80
81
                $asset = new Asset();
82
                $asset->setCategory(Asset::SCORM)
83
                    ->setTitle($zipName)
84
                    ->setFile($file)
85
                    ->setCompressed(true);
86
87
                $assetRepo->update($asset);
88
89
                $this->log("Asset created: id=".$asset->getId());
90
91
                $assetRepo->unZipFile($asset, basename($path));
92
                $this->log("Asset unzipped for: ".$asset->getTitle());
93
94
                $lp->setAsset($asset);
95
                $lp->setPath(basename($path).'/.');
96
                $this->entityManager->persist($lp);
97
                $this->entityManager->flush();
98
99
                $this->log("LP updated id=$lpId linked to asset_id=".$asset->getId());
100
            }
101
        }
102
103
        $this->log('Finished SCORM migration.');
104
    }
105
106
    private function zipFolder(string $folderPath, string $zipPath): void
107
    {
108
        $zip = new \ZipArchive();
109
        if ($zip->open($zipPath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) !== true) {
110
            $this->log("Cannot create ZIP file: $zipPath");
111
            return;
112
        }
113
114
        $files = new \RecursiveIteratorIterator(
115
            new \RecursiveDirectoryIterator($folderPath, \RecursiveDirectoryIterator::SKIP_DOTS),
116
            \RecursiveIteratorIterator::LEAVES_ONLY
117
        );
118
119
        foreach ($files as $file) {
120
            $filePath = $file->getRealPath();
121
            $relativePath = substr($filePath, strlen($folderPath) + 1);
122
            $zip->addFile($filePath, $relativePath);
123
        }
124
125
        $zip->close();
126
    }
127
128
    private function log(string $message): void
129
    {
130
        error_log('[SCORM Migration] ' . $message);
131
    }
132
133
    public function down(Schema $schema): void {}
134
}
135