Passed
Push — master ( 6304f4...fc13ff )
by Julito
08:01
created

Version20191206150030   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 34
c 1
b 0
f 0
dl 0
loc 50
rs 10
wmc 7

1 Method

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