/lib/io/dir.php

https://github.com/denibrain/fowork · PHP · 93 lines · 81 code · 12 blank · 0 comment · 22 complexity · e4d52d1fc930368f04e251e1e8bc7f8d MD5 · raw file

  1. <?php
  2. namespace FW\IO;
  3. class Dir extends FileSystemItem implements \Iterator {
  4. private $data;
  5. private $dir = 0;
  6. private $no = 0;
  7. function __destruct() {
  8. if ($this->dir) $this->dir->close();
  9. }
  10. function create($mode = 0755, $user = '') {
  11. if ($this->exists)
  12. chmod($this->name, $mode);
  13. else
  14. mkdir($this->name, $mode, true);
  15. if ($user) chown($this->name, $user);
  16. }
  17. function createChild($name) {
  18. $d = new Dir($this->name.'/'.$name);
  19. $d->create();
  20. return $d;
  21. }
  22. function delete() {
  23. if (!$this->exists) throw new \Exception("Directory $this->name not exists!");
  24. foreach($this as $item) {
  25. if (is_link($item->name)) unlink($item->name);
  26. else $item->delete();
  27. }
  28. \rmdir($this->name);
  29. }
  30. function deleteFiles($mask, $recursive = false) {
  31. if (!$this->exists) throw new \Exception("Directory $this->name not exists!");
  32. foreach($this as $item) {
  33. if (preg_match($mask, $item->basename)) $item->delete();
  34. elseif ($recursive && $item instanceof Dir) $item->deleteFiles($mask, true);
  35. }
  36. }
  37. public function key() { return $this->no; }
  38. public function valid() {
  39. do {
  40. $this->data = $this->dir->read();
  41. } while ($this->data && ($this->data == '.' || $this->data == '..'));
  42. return false !== ($this->data);
  43. }
  44. public function rewind() {
  45. $this->no = 0;
  46. if(file_exists($this->name)) {
  47. if (!$this->dir)
  48. $this->dir = \dir($this->name);
  49. else
  50. $this->dir->rewind();
  51. }
  52. }
  53. public function next() {
  54. $this->no++;
  55. }
  56. public function current() {
  57. $name = "$this->name/$this->data";
  58. if (is_dir($name)) return new Dir($name);
  59. return new File($name);
  60. }
  61. function copyTo($target) {
  62. $d = new Dir($target);
  63. if (!$d->exists) $d->create();
  64. $stack = array(array($this, $d));
  65. while ($stack) {
  66. list($dir, $target) = array_pop($stack);
  67. foreach ($dir as $item) {
  68. if (\is_link($item->name)) {
  69. $source = \readlink($item->name);
  70. \symlink($source, $target->name."/".$item->basename);
  71. }
  72. elseif ($item instanceof Dir) {
  73. \array_push ($stack, array($item, $target->createChild($item->basename)));
  74. }
  75. else {
  76. $item->copyTo($target->name."/".$item->basename);
  77. }
  78. }
  79. }
  80. }
  81. }