Passed
Push — master ( 240c83...03f39b )
by Mathias
06:41
created

MigrationHandler::findOrCreate()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 5
dl 0
loc 11
rs 10
c 1
b 0
f 1
cc 3
nc 2
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yawik\Migration\Handler;
6
7
use Doctrine\ODM\MongoDB\DocumentManager;
8
use Doctrine\Persistence\ObjectRepository;
9
use InvalidArgumentException;
10
use Psr\Container\ContainerInterface;
11
use Yawik\Migration\Contracts\MigratorInterface;
12
use Yawik\Migration\Entity\Migration;
13
14
class MigrationHandler
15
{
16
    private DocumentManager $dm;
17
18
    private ObjectRepository $repo;
19
20
    public function __construct(
21
        DocumentManager $dm
22
    )
23
    {
24
        $this->dm = $dm;
25
        $this->repo = $dm->getRepository(Migration::class);
26
    }
27
28
    public static function factory(ContainerInterface $container)
29
    {
30
        $dm = $container->get(DocumentManager::class);
31
32
        return new self($dm);
33
    }
34
35
    /**
36
     * @param MigratorInterface $migrator
37
     * @param bool $create
38
     * @return null|object|Migration
39
     */
40
    public function findOrCreate(MigratorInterface $migrator, bool $create = false)
41
    {
42
        $ob =  $this->repo->findOneBy([
43
            'class' => get_class($migrator)
44
        ]);
45
46
        if(is_null($ob) && $create){
47
            $ob = $this->create($migrator);
48
        }
49
50
        return $ob;
51
    }
52
53
    public function create(MigratorInterface $migrator): Migration
54
    {
55
        $dm = $this->dm;
56
        $ob = new Migration(
57
            get_class($migrator),
58
            $migrator->version(),
59
            $migrator->getDescription(),
60
        );
61
62
        $dm->persist($ob);
63
        $dm->flush();
64
65
        return $ob;
66
    }
67
68
    public function migrated(MigratorInterface $migrator): Migration
69
    {
70
        $migration = $this->findOrCreate($migrator);
71
        if(!is_null($migration)){
72
            $dm = $this->dm;
73
            $migration->setMigrated(true);
74
            $migration->setMigratedAt(new \DateTime());
75
            $dm->persist($migration);
76
            $dm->flush();
77
            return $migration;
78
        }
79
        throw new InvalidArgumentException(sprintf(
80
            "Migration data for '%s' is not exists in database.",
81
            get_class($migrator)
82
        ));
83
    }
84
}