Dirs.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\System;
  7. class Dirs
  8. {
  9. /**
  10. * @param string[]|string $dirname
  11. * @return bool
  12. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  13. * @SuppressWarnings(PHPMD.NPathComplexity)
  14. * @SuppressWarnings(PHPMD.ShortMethodName)
  15. */
  16. public static function rm($dirname)
  17. {
  18. if (is_array($dirname)) {
  19. $dirname = $dirname[1];
  20. }
  21. // Sanity check
  22. if (!@file_exists($dirname)) {
  23. return false;
  24. }
  25. // Simple delete for a file
  26. if (@is_file($dirname) || @is_link($dirname)) {
  27. return unlink($dirname);
  28. }
  29. // Create and iterate stack
  30. $stack = [$dirname];
  31. while ($entry = array_pop($stack)) {
  32. // Watch for symlinks
  33. if (@is_link($entry)) {
  34. @unlink($entry);
  35. continue;
  36. }
  37. // Attempt to remove the directory
  38. if (@rmdir($entry)) {
  39. continue;
  40. }
  41. // Otherwise add it to the stack
  42. $stack[] = $entry;
  43. $dh = opendir($entry);
  44. while (false !== ($child = readdir($dh))) {
  45. // Ignore pointers
  46. if ($child === '.' || $child === '..') {
  47. continue;
  48. }
  49. // Unlink files and add directories to stack
  50. $child = $entry . '/' . $child;
  51. if (is_dir($child) && !is_link($child)) {
  52. $stack[] = $child;
  53. } else {
  54. @unlink($child);
  55. }
  56. }
  57. @closedir($dh);
  58. }
  59. return true;
  60. }
  61. /**
  62. * Attempts to create the directory
  63. *
  64. * @param string $path
  65. * @param bool $recursive
  66. * @param int $mode
  67. * @return true
  68. * @throws \Exception
  69. */
  70. public static function mkdirStrict($path, $recursive = true, $mode = 0777)
  71. {
  72. $exists = file_exists($path);
  73. if ($exists && is_dir($path)) {
  74. return true;
  75. }
  76. if ($exists && !is_dir($path)) {
  77. throw new \Exception("'{$path}' already exists, should be a dir, not a file!");
  78. }
  79. $out = @mkdir($path, $mode, $recursive);
  80. if (false === $out) {
  81. throw new \Exception("Can't create dir: '{$path}'");
  82. }
  83. return true;
  84. }
  85. /**
  86. * @param string $source
  87. * @param string $dest
  88. * @return void
  89. * @throws \Exception
  90. * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  91. */
  92. public static function copyFileStrict($source, $dest)
  93. {
  94. $exists = file_exists($source);
  95. if (!$exists) {
  96. throw new \Exception('No file exists: ' . $exists);
  97. }
  98. }
  99. }