PageRenderTime 61ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/core/filesystem/FileSystem.php

https://bitbucket.org/nlenardou/piko
PHP | 120 lines | 92 code | 20 blank | 8 comment | 13 complexity | 53121e90a51b3d37e644fef9815ef784 MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php
  2. class FileSystem
  3. {
  4. public static function ensureFilePutContents($file, $content)
  5. {
  6. $folder = pathinfo($file, PATHINFO_DIRNAME);
  7. if(! is_dir($folder) )
  8. {
  9. if( self::makeDir($folder) === false)
  10. {
  11. return false;
  12. }
  13. }
  14. return file_put_contents($file, $content);
  15. }
  16. public static function makeDir($directory, $rights = 0755, $recursive = true)
  17. {
  18. return mkdir($directory, $rights, $recursive);
  19. }
  20. public static function invalidateItem($path, $removeIfNotEmpty = true)
  21. {
  22. return self::removeItem($path, $removeIfNotEmpty, false);
  23. }
  24. public static function removeItem($path, $removeIfNotEmpty = true, $purge = true)
  25. {
  26. if(is_dir($path))
  27. {
  28. $subitems = scandir($path);
  29. if(! $removeIfNotEmpty && count($subitems) > 0)
  30. {
  31. return false;
  32. }
  33. foreach($subitems as $subitem)
  34. {
  35. if($subitem != '.' && $subitem != '..')
  36. {
  37. $subitem = self::sanitizeFolder($path) . $subitem;
  38. self::removeItem($subitem, $removeIfNotEmpty, $purge);
  39. }
  40. }
  41. if($purge === true)
  42. {
  43. self::removeEmptyDir($path);
  44. }
  45. }
  46. elseif(file_exists($path))
  47. {
  48. if($purge === true)
  49. {
  50. self::removeFile($path);
  51. }
  52. else
  53. {
  54. self::invalidateFile($path);
  55. }
  56. }
  57. }
  58. public static function removeEmptyDir($directory)
  59. {
  60. return rmdir($directory);
  61. }
  62. public static function removeFile($file)
  63. {
  64. return unlink($file);
  65. }
  66. public static function invalidateFile($file)
  67. {
  68. return touch($file, 0);
  69. }
  70. /**
  71. * Fonction récursive de glob : permet de lister rapidement les fichiers d'un répertoire et de ses sous répertoires.
  72. *
  73. * @param comme glob, voir http://fr.php.net/glob
  74. */
  75. public static function rglob($pattern, $flags = 0)
  76. {
  77. // separator
  78. $path = dirname($pattern);
  79. $pattern_name = '/' . basename($pattern);
  80. $return = array();
  81. // Files
  82. $return = glob($path . $pattern_name, $flags);
  83. // Subdirs
  84. $subdirs = glob($path . '/*', GLOB_ONLYDIR);
  85. $nbSubdirs = count($subdirs);
  86. for ( $i = 0 ; $i < $nbSubdirs ; $i++ )
  87. {
  88. $return = array_merge($return, self::rglob($subdirs[$i] . $pattern_name, $flags));
  89. }
  90. return $return;
  91. }
  92. public static function sanitizeFolder($folder)
  93. {
  94. if(substr($folder, -1) !== DIRECTORY_SEPARATOR)
  95. {
  96. $folder .= DIRECTORY_SEPARATOR;
  97. }
  98. return $folder;
  99. }
  100. }