Completed
Push — master ( 81db43...f030be )
by Aleh
12s
created

Persister::load()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 2
Metric Value
c 2
b 0
f 2
dl 0
loc 16
rs 9.2
cc 4
eloc 10
nc 4
nop 1
1
<?php
2
3
namespace Padawan\Framework\Domain\Project;
4
5
6
use Padawan\Framework\Utils\PathResolver;
7
use Padawan\Domain\Project;
8
use \__PHP_Incomplete_Class;
9
use Amp\File;
10
11
/**
12
 * Class Persister
13
 */
14
class Persister
15
{
16
    const PADAWAN_DIR = ".padawan";
17
    const INDEX_FILE = "project";
18
19
    public function __construct(PathResolver $path)
20
    {
21
        $this->path = $path;
22
    }
23
24
    public function save(Project $project)
25
    {
26
        $this->checkForPadawanDir($project->getRootFolder());
27
        return File\put(
28
            $this->getProjectIndexFilePath($project->getRootFolder()),
29
            $this->serialize($project)
30
        );
31
    }
32
33
    public function load($rootDir)
34
    {
35
        try {
36
            $project = $this->unserialize(
37
                $this->readFromFile($this->getProjectIndexFilePath($rootDir))
38
            );
39
            if ($project instanceof __PHP_Incomplete_Class
40
                || $project->getIndex() instanceof __PHP_Incomplete_Class
41
            ) {
42
                return;
43
            }
44
            return $project;
45
        } catch (\Exception $e) {
46
            return;
47
        }
48
    }
49
50
    private function unserialize($rawProject)
51
    {
52
        return unserialize($rawProject);
53
    }
54
55
    private function getProjectIndexFilePath($rootDir)
56
    {
57
        return $this->path->join([
58
            $rootDir,
59
            self::PADAWAN_DIR,
60
            self::INDEX_FILE
61
        ]);
62
    }
63
64
    private function serialize(Project $project)
65
    {
66
        return serialize($project);
67
    }
68
69
    private function readFromFile($filename)
70
    {
71
        return $this->path->read($filename);
72
    }
73
74
    private function checkForPadawanDir($dir)
75
    {
76
        $padawanDir = $this->path->join([$dir, self::PADAWAN_DIR]);
77
        if ($this->path->isDir($padawanDir)) {
78
            return;
79
        }
80
        if ($this->path->exists($padawanDir)) {
81
            $this->path->remove($padawanDir);
82
        }
83
        $this->path->create($padawanDir, true);
84
    }
85
86
    /**
87
     *
88
     * @var PathResolver
89
     */
90
    private $path;
91
}
92