Completed
Push — master ( 3bba38...f9f96f )
by Dev
04:14
created

Element::deleteElement()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 1
c 1
b 0
f 1
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 3
cp 0
crap 2
rs 10
1
<?php
2
3
namespace PiedWeb\CMSBundle\TemplateEditor;
4
5
class Element
6
{
7
8
    /**
9
     * @var string
10
     */
11
    protected $path;
12
13
    /**
14
     * @var string
15
     */
16
    protected $code;
17
18
    /**
19
     * @var string
20
     */
21
    protected $templateDir;
22
23
    /**
24
     * @var string
25
     */
26
    protected $unlink;
27
28
    public function __construct($templateDir, $path = null)
29
    {
30
        $this->templateDir = realpath($templateDir);
31
        $this->path        = substr($path, strlen($this->templateDir));
32
        $this->code        = $this->loadCode();
33
    }
34
35
    protected function loadCode()
36
    {
37
        if ($this->path !== null && file_exists($this->getTemplateDir().$this->getPath())) {
38
            return file_get_contents($this->getTemplateDir().$this->getPath());
39
        }
40
41
        return '';
42
    }
43
44
    protected function getTemplateDir()
45
    {
46
        return $this->templateDir;
47
    }
48
49
    public function getPath(): ?string
50
    {
51
        return $this->path;
52
    }
53
54
    public function getEncodedPath(): ?string
55
    {
56
        return md5($this->path);
57
    }
58
59
    public function setPath(string $path)
60
    {
61
        if ($this->path === null) {
62
            $this->path = $path;
63
        } else {
64
            if ($this->path != $path) {
65
                if (file_exists($this->getTemplateDir().$path)) {
66
                    throw new \Exception('file ever exist');
67
                } else {
68
                    $this->unlink = $this->getTemplateDir().$this->path;
69
                    $this->path = $path;
70
                }
71
            }
72
        }
73
74
        return $this;
75
    }
76
77
    public function getCode()
78
    {
79
        return $this->code;
80
    }
81
82
    public function setCode(string $code)
83
    {
84
        $this->code = $code;
85
    }
86
87
    public function storeElement()
88
    {
89
        if ($this->unlink) { // for rename
90
            unlink($this->unlink);
91
        }
92
93
        return file_put_contents($this->getTemplateDir().$this->path, $this->code);
94
    }
95
96
    public function deleteElement()
97
    {
98
        return unlink($this->getTemplateDir().$this->path);
99
    }
100
}
101