File size: 2,405 Bytes
d2897cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php

declare(strict_types=1);

namespace Mautic\IntegrationsBundle\Migration;

use Doctrine\ORM\EntityManager;
use Mautic\IntegrationsBundle\Exception\PathNotFoundException;

class Engine
{
    private string $migrationsPath;

    public function __construct(
        private EntityManager $entityManager,
        private string $tablePrefix,
        string $pluginPath,
        private string $bundleName
    ) {
        $this->migrationsPath = $pluginPath.'/Migrations/';
    }

    /**
     * Run available migrations.
     */
    public function up(): void
    {
        try {
            $migrationClasses = $this->getMigrationClasses();
        } catch (PathNotFoundException $e) {
            return;
        }

        if (!$migrationClasses) {
            return;
        }

        $this->entityManager->beginTransaction();

        try {
            foreach ($migrationClasses as $migrationClass) {
                /** @var AbstractMigration $migration */
                $migration = new $migrationClass($this->entityManager, $this->tablePrefix);

                if ($migration->shouldExecute()) {
                    $migration->execute();
                }
            }

            $this->entityManager->commit();
        } catch (\Doctrine\DBAL\Exception $e) {
            $this->entityManager->rollback();

            throw $e;
        }
    }

    /**
     * Get migration classes to proceed.
     *
     * @return string[]
     */
    private function getMigrationClasses(): array
    {
        $migrationFileNames = $this->getMigrationFileNames();
        $migrationClasses   = [];

        foreach ($migrationFileNames as $fileName) {
            require_once $this->migrationsPath.$fileName;
            $className          = preg_replace('/\\.[^.\\s]{3,4}$/', '', $fileName);
            $className          = 'MauticPlugin\\'.$this->bundleName."\Migrations\\{$className}";
            $migrationClasses[] = $className;
        }

        return $migrationClasses;
    }

    /**
     * Get migration file names.
     *
     * @return string[]
     */
    private function getMigrationFileNames(): array
    {
        $fileNames = @scandir($this->migrationsPath);

        if (false === $fileNames) {
            throw new PathNotFoundException(sprintf("'%s' directory not found", $this->migrationsPath));
        }

        return array_diff($fileNames, ['.', '..']);
    }
}