Completed
Push — master ( 2b4213...6816c3 )
by Aleh
9s
created

Persister   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 2
Bugs 1 Features 1
Metric Value
wmc 12
c 2
b 1
f 1
lcom 1
cbo 2
dl 0
loc 73
rs 10

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A save() 0 5 1
A load() 0 14 3
A unserialize() 0 4 1
A getProjectIndexFilePath() 0 8 1
A serialize() 0 4 1
A readFromFile() 0 4 1
A checkForPadawanDir() 0 11 3
1
<?php
2
3
namespace Padawan\Framework\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($this->getProjectIndexFilePath($project->getRootFolder()), $this->serialize($project));
28
    }
29
30
    public function load($rootDir)
31
    {
32
        try {
33
            $project = $this->unserialize(
34
                $this->readFromFile($this->getProjectIndexFilePath($rootDir))
35
            );
36
            if ($project instanceof __PHP_Incomplete_Class) {
37
                return;
38
            }
39
            return $project;
40
        } catch (\Exception $e) {
41
            return;
42
        }
43
    }
44
45
    private function unserialize($rawProject)
46
    {
47
        return unserialize($rawProject);
48
    }
49
50
    private function getProjectIndexFilePath($rootDir)
51
    {
52
        return $this->path->join([
53
            $rootDir,
54
            self::PADAWAN_DIR,
55
            self::INDEX_FILE
56
        ]);
57
    }
58
59
    private function serialize(Project $project)
60
    {
61
        return serialize($project);
62
    }
63
64
    private function readFromFile($filename)
65
    {
66
        return $this->path->read($filename);
67
    }
68
69
    private function checkForPadawanDir($dir)
70
    {
71
        $padawanDir = $this->path->join([$dir, self::PADAWAN_DIR]);
72
        if ($this->path->isDir($padawanDir)) {
73
            return;
74
        }
75
        if ($this->path->exists($padawanDir)) {
76
            $this->path->remove($padawanDir);
77
        }
78
        $this->path->create($padawanDir, true);
79
    }
80
81
    /**
82
     *
83
     * @var PathResolver
84
     */
85
    private $path;
86
}
87