Passed
Push — master ( 6c23c3...c1688f )
by Julito
09:45
created

Version20191206150030   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 34
c 2
b 0
f 0
dl 0
loc 53
rs 10
wmc 8

2 Methods

Rating   Name   Duplication   Size   Complexity  
B up() 0 46 7
A getDescription() 0 3 1
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\ExtraFieldValues;
11
use Chamilo\CoreBundle\Migrations\AbstractMigrationChamilo;
12
use Doctrine\DBAL\Schema\Schema;
13
use ExtraField;
14
use Symfony\Component\HttpFoundation\File\UploadedFile;
15
16
class Version20191206150030 extends AbstractMigrationChamilo
17
{
18
    public function getDescription(): string
19
    {
20
        return 'ExtraFieldValues changes';
21
    }
22
23
    public function up(Schema $schema): void
24
    {
25
        // Migrate extra field fields
26
        $container = $this->getContainer();
27
        $doctrine = $container->get('doctrine');
28
        $em = $doctrine->getManager();
29
30
        $kernel = $container->get('kernel');
31
        $rootPath = $kernel->getProjectDir();
32
33
        $batchSize = self::BATCH_SIZE;
34
        $counter = 1;
35
        $q = $em->createQuery('SELECT v FROM Chamilo\CoreBundle\Entity\ExtraFieldValues v');
36
37
        $fieldWithFiles = ExtraField::getExtraFieldTypesWithFiles();
38
39
        /** @var ExtraFieldValues $item */
40
        foreach ($q->toIterable() as $item) {
41
            if (\in_array($item->getField()->getFieldType(), $fieldWithFiles, true)) {
42
                $path = $item->getValue();
43
                if (empty($path)) {
44
                    continue;
45
                }
46
                $filePath = $rootPath.'/app/upload/'.$path;
47
                if (file_exists($filePath) && !is_dir($filePath)) {
48
                    $fileName = basename($path);
49
                    $mimeType = mime_content_type($filePath);
50
                    $file = new UploadedFile($filePath, $fileName, $mimeType, null, true);
51
                    $asset = new Asset();
52
                    $asset
53
                        ->setCategory(Asset::EXTRA_FIELD)
54
                        ->setTitle($fileName)
55
                        ->setFile($file)
56
                    ;
57
                    $em->persist($asset);
58
                    $em->flush();
59
                    $item->setValue((string) $asset->getId());
60
                    $em->persist($item);
61
                }
62
            }
63
64
            if (0 === $counter % $batchSize) {
65
                $em->flush();
66
                $em->clear(); // Detaches all objects from Doctrine!
67
            }
68
            $counter++;
69
        }
70
    }
71
}
72