forked from horde/components
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathWrapperTrait.php
124 lines (114 loc) · 2.78 KB
/
WrapperTrait.php
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
<?php
/**
* Copyright 2017 Horde LLC (http://www.horde.org/)
*
* See the enclosed file LICENSE for license information (LGPL). If you
* did not receive this file, see http://www.horde.org/licenses/lgpl21.
*
* @category Horde
* @package Components
* @author Jan Schneider <[email protected]>
* @license http://www.horde.org/licenses/lgpl21 LGPL 2.1
*/
namespace Horde\Components;
use Horde\Components\Wrapper;
/**
* Trait for the component file wrappers.
*
* @category Horde
* @package Components
* @author Jan Schneider <[email protected]>
* @license http://www.horde.org/licenses/lgpl21 LGPL 2.1
*/
trait WrapperTrait
{
/**
* Full path to the file.
*
* @var string
*/
protected $_file;
/**
* Returns the full path to the file.
*
* @return string Path to the file.
*/
public function getFullPath()
{
return $this->_file;
}
/**
* Returns the local path to the file inside the package.
*
* @param string $dir The package directory.
*
* @return string Path to the file.
*/
public function getLocalPath($dir)
{
return preg_replace(
'|^' . preg_quote(rtrim($dir, '/'), '|') . '/|',
'',
$this->_file
);
}
/**
* Returns the file name.
*
* @return string The file name.
*/
public function getFileName()
{
return basename((string) $this->_file);
}
/**
* Returns whether the file exists.
*
* @return boolean True if the file exists.
*/
public function exists()
{
return file_exists($this->_file);
}
/**
* Returns a diff between the saved and the current version of the file.
*
*
* @return string File diff.
*/
public function diff(Wrapper $wrapper = null)
{
$renderer = new \Horde_Text_Diff_Renderer_Unified();
if ($wrapper) {
$old = explode("\n", trim($wrapper, "\n"));
} elseif ($this->exists()) {
$old = file($this->getFullPath());
} else {
$old = [];
}
return $renderer->render(
new \Horde_Text_Diff(
'auto',
[$old, explode("\n", rtrim((string) $this, "\n"))]
)
);
}
/**
* Saves this object to the file.
*/
public function save()
{
$contents = (string)$this;
if (!strlen($contents) && !$this->exists()) {
return;
}
if (!is_dir(dirname((string) $this->_file))) {
mkdir(dirname((string) $this->_file), 0777, true);
}
file_put_contents($this->_file, $contents);
}
/**
* Returns the file contents.
*/
abstract public function __toString();
}