FolderLib.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. App::uses('Folder', 'Utility');
  3. /**
  4. * Folder lib with a few custom improvements
  5. */
  6. class FolderLib extends Folder {
  7. /**
  8. * Empty the folder.
  9. * Instead of deleting the folder itself as delete() does,
  10. * this method only removes its content recursivly.
  11. *
  12. * Note: It skips hidden folders (starting with a . dot).
  13. *
  14. * @return bool Success or null on invalid folder
  15. */
  16. public function clear($path = null) {
  17. if (!$path) {
  18. $path = $this->pwd();
  19. }
  20. if (!$path) {
  21. return null;
  22. }
  23. $path = Folder::slashTerm($path);
  24. if (!is_dir($path)) {
  25. return null;
  26. }
  27. $normalFiles = glob($path . '*');
  28. $hiddenFiles = glob($path . '\.?*');
  29. $normalFiles = $normalFiles ? $normalFiles : [];
  30. $hiddenFiles = $hiddenFiles ? $hiddenFiles : [];
  31. $files = array_merge($normalFiles, $hiddenFiles);
  32. foreach ($files as $file) {
  33. if (preg_match('/(\.|\.\.)$/', $file)) {
  34. continue;
  35. }
  36. if (is_file($file)) {
  37. if (@unlink($file)) {
  38. $this->_messages[] = __d('tools', '%s removed', $file);
  39. } else {
  40. $this->_errors[] = __d('tools', '%s NOT removed', $file);
  41. }
  42. } elseif (is_dir($file) && $this->delete($file) === false) {
  43. return false;
  44. }
  45. }
  46. return true;
  47. }
  48. }