|
1
|
|
|
<?php |
|
2
|
|
|
namespace phootwork\file; |
|
3
|
|
|
|
|
4
|
|
|
use \DateTime; |
|
5
|
|
|
use phootwork\file\exception\FileException; |
|
6
|
|
|
|
|
7
|
|
|
class File { |
|
8
|
|
|
|
|
9
|
|
|
use FileOperationTrait; |
|
10
|
|
|
|
|
11
|
|
|
public function __construct($filename) { |
|
12
|
|
|
$this->init($filename); |
|
13
|
|
|
} |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* Reads contents from the file |
|
17
|
|
|
* |
|
18
|
|
|
* @throws FileException |
|
19
|
|
|
* @return string contents |
|
20
|
|
|
*/ |
|
21
|
|
|
public function read() { |
|
22
|
|
|
if (!$this->exists()) { |
|
23
|
|
|
throw new FileException(sprintf('File does not exist: %s', $this->getFilename())); |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
if (!$this->isReadable()) { |
|
27
|
|
|
throw new FileException(sprintf('You don\'t have permissions to access %s file', $this->getFilename())); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
return file_get_contents($this->pathname); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* Writes contents to the file |
|
35
|
|
|
* |
|
36
|
|
|
* @param string $contents |
|
37
|
|
|
* @return $this |
|
38
|
|
|
*/ |
|
39
|
|
|
public function write($contents) { |
|
40
|
|
|
$dir = new Directory($this->getDirname()); |
|
41
|
|
|
$dir->make(); |
|
42
|
|
|
|
|
43
|
|
|
file_put_contents($this->pathname, $contents); |
|
44
|
|
|
return $this; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* Touches the file |
|
49
|
|
|
* |
|
50
|
|
|
* @param int|DateTime $created |
|
51
|
|
|
* @param int|DateTime $lastAccessed |
|
52
|
|
|
* @throws FileException when something goes wrong |
|
53
|
|
|
*/ |
|
54
|
|
|
public function touch($created = null, $lastAccessed = null) { |
|
55
|
|
|
$created = $created instanceof DateTime |
|
56
|
|
|
? $created->getTimestamp() |
|
57
|
|
|
: ($created === null ? time() : $created); |
|
58
|
|
|
$lastAccessed = $lastAccessed instanceof DateTime |
|
59
|
|
|
? $lastAccessed->getTimestamp() |
|
60
|
|
|
: ($lastAccessed === null ? time() : $lastAccessed); |
|
61
|
|
|
|
|
62
|
|
|
if (!@touch($this->pathname, $created, $lastAccessed)) { |
|
63
|
|
|
throw new FileException(sprintf('Failed to touch file at %s', $this->pathname)); |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
/** |
|
68
|
|
|
* Deletes the file |
|
69
|
|
|
* |
|
70
|
|
|
* @throws FileException when something goes wrong |
|
71
|
|
|
*/ |
|
72
|
|
|
public function delete() { |
|
73
|
|
|
if (!@unlink($this->pathname)) { |
|
74
|
|
|
throw new FileException(sprintf('Failed to delete file at %s', $this->pathname)); |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
/** |
|
79
|
|
|
* String representation of this file as pathname |
|
80
|
|
|
*/ |
|
81
|
|
|
public function __toString() { |
|
82
|
|
|
return $this->pathname; |
|
83
|
|
|
} |
|
84
|
|
|
|
|
85
|
|
|
} |
|
86
|
|
|
|