1
|
|
|
<?php |
2
|
|
|
namespace phootwork\file; |
3
|
|
|
|
4
|
|
|
use \DirectoryIterator; |
5
|
|
|
use phootwork\file\exception\FileException; |
6
|
|
|
|
7
|
|
|
class Directory implements \Iterator { |
8
|
|
|
|
9
|
|
|
use FileOperationTrait; |
10
|
|
|
|
11
|
|
|
private $iterator; |
12
|
|
|
|
13
|
|
|
public function __construct($filename) { |
14
|
|
|
$this->init($filename); |
15
|
|
|
} |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Creates the directory |
19
|
|
|
* |
20
|
|
|
* @throws FileException when something goes wrong |
21
|
|
|
* @param number $mode |
22
|
|
|
*/ |
23
|
|
|
public function make($mode = 0777) { |
24
|
|
|
if (!$this->exists() && !@mkdir($this->pathname, $mode, true)) { |
25
|
|
|
throw new FileException(sprintf('Failed to create directory "%s"', $this->pathname)); |
26
|
|
|
} |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Recursively deletes the directory |
31
|
|
|
* |
32
|
|
|
* @throws FileException when something goes wrong |
33
|
|
|
*/ |
34
|
|
|
public function delete() { |
35
|
|
|
foreach ($this as $file) { |
36
|
|
|
if (!$file->isDot()) { |
37
|
|
|
$file->delete(); |
38
|
|
|
} |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
if (!@rmdir($this->pathname)) { |
42
|
|
|
throw new FileException(sprintf('Failed to delete directory "%s"', $this->pathname)); |
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Returns a directory iterator |
48
|
|
|
* |
49
|
|
|
* @return DirectoryIterator |
50
|
|
|
*/ |
51
|
|
|
private function getIterator() { |
52
|
|
|
if ($this->iterator === null) { |
53
|
|
|
$this->iterator = new DirectoryIterator($this->pathname); |
54
|
|
|
} |
55
|
|
|
return $this->iterator; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @return FileDescriptor |
60
|
|
|
* @internal |
61
|
|
|
*/ |
62
|
|
|
public function current () { |
63
|
|
|
return FileDescriptor::fromFileInfo($this->getIterator()->current()); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* @internal |
68
|
|
|
*/ |
69
|
|
|
public function key () { |
70
|
|
|
return $this->getIterator()->key(); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* @internal |
75
|
|
|
*/ |
76
|
|
|
public function next () { |
77
|
|
|
return $this->getIterator()->next(); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* @internal |
82
|
|
|
*/ |
83
|
|
|
public function rewind () { |
84
|
|
|
return $this->getIterator()->rewind(); |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
/** |
88
|
|
|
* @internal |
89
|
|
|
*/ |
90
|
|
|
public function valid () { |
91
|
|
|
return $this->getIterator()->valid(); |
92
|
|
|
} |
93
|
|
|
|
94
|
|
|
/** |
95
|
|
|
* String representation of this directory as pathname |
96
|
|
|
*/ |
97
|
|
|
public function __toString() { |
98
|
|
|
return $this->pathname; |
99
|
|
|
} |
100
|
|
|
} |
101
|
|
|
|