-
Notifications
You must be signed in to change notification settings - Fork 0
/
File.php
103 lines (85 loc) · 2.28 KB
/
File.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
<?php namespace Devtools;
use Exception;
class File
{
public $path;
public $contents;
public $name;
public function __construct($path = null)
{
if (!is_null($path)) {
$this->open($path);
}
}
public function open($path)
{
$this->path = $path;
$this->contents = '';
$this->name();
if ($this->exists()) {
$this->read();
}
return $this;
}
public function contents($contents, $doNotOverwrite = true)
{
if (!$doNotOverwrite && !file_put_contents($this->path, $contents)) {
throw new Exception('Contents could not be written to file.');
} else {
$this->contents = $contents;
return $this->safePersist($this->path);
}
$this->contents = $contents;
}
public function exists()
{
return file_exists($this->path);
}
public function delete()
{
if (file_exists($this->path)) {
unlink($this->path);
}
}
private function name()
{
$this->name = basename($this->path);
}
private function read()
{
$contents = file_get_contents($this->path);
if (!$contents) {
throw new Exception('File could not be read.');
}
$this->contents = $contents;
}
public function copyTo($newPath)
{
$this->path = $newPath;
$this->name();
$this->contents($this->contents);
}
public function parsePath($path)
{
$extensionStarts = strrpos($path, '.');
return array(
'prefix' => substr($path, 0, $extensionStarts),
'extension' => substr($path, $extensionStarts)
);
}
public function safePersist($path)
{
if (!file_exists($path)) {
file_put_contents($path, $this->contents);
} else {
extract($this->parsePath($path));
$revision = 0;
while (file_exists("{$prefix}.rev{$revision}{$extension}")) {
$revision++;
}
file_put_contents("{$prefix}.rev{$revision}{$extension}", file_get_contents($path));
file_put_contents($path, $this->contents);
}
return isset($revision) ? $revision : 'new';
}
}