PageRenderTime 55ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/src/Composer/Util/Filesystem.php

https://github.com/krunasek/composer
PHP | 312 lines | 203 code | 43 blank | 66 comment | 37 complexity | 124e45eb8afc6fd055c94e9bdfa519c3 MD5 | raw file
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer\Util;
  12. use RecursiveDirectoryIterator;
  13. use RecursiveIteratorIterator;
  14. /**
  15. * @author Jordi Boggiano <j.boggiano@seld.be>
  16. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  17. */
  18. class Filesystem
  19. {
  20. private $processExecutor;
  21. public function __construct(ProcessExecutor $executor = null)
  22. {
  23. $this->processExecutor = $executor ?: new ProcessExecutor();
  24. }
  25. public function remove($file)
  26. {
  27. if (is_dir($file)) {
  28. return $this->removeDirectory($file);
  29. }
  30. if (file_exists($file)) {
  31. return unlink($file);
  32. }
  33. return false;
  34. }
  35. /**
  36. * Recursively remove a directory
  37. *
  38. * Uses the process component if proc_open is enabled on the PHP
  39. * installation.
  40. *
  41. * @param string $directory
  42. * @return bool
  43. */
  44. public function removeDirectory($directory)
  45. {
  46. if (!is_dir($directory)) {
  47. return true;
  48. }
  49. if (!function_exists('proc_open')) {
  50. return $this->removeDirectoryPhp($directory);
  51. }
  52. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  53. $cmd = sprintf('rmdir /S /Q %s', escapeshellarg(realpath($directory)));
  54. } else {
  55. $cmd = sprintf('rm -rf %s', escapeshellarg($directory));
  56. }
  57. $result = $this->getProcess()->execute($cmd, $output) === 0;
  58. // clear stat cache because external processes aren't tracked by the php stat cache
  59. clearstatcache();
  60. return $result && !is_dir($directory);
  61. }
  62. /**
  63. * Recursively delete directory using PHP iterators.
  64. *
  65. * Uses a CHILD_FIRST RecursiveIteratorIterator to sort files
  66. * before directories, creating a single non-recursive loop
  67. * to delete files/directories in the correct order.
  68. *
  69. * @param string $directory
  70. * @return bool
  71. */
  72. public function removeDirectoryPhp($directory)
  73. {
  74. $it = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS);
  75. $ri = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
  76. foreach ($ri as $file) {
  77. if ($file->isDir()) {
  78. rmdir($file->getPathname());
  79. } else {
  80. unlink($file->getPathname());
  81. }
  82. }
  83. return rmdir($directory);
  84. }
  85. public function ensureDirectoryExists($directory)
  86. {
  87. if (!is_dir($directory)) {
  88. if (file_exists($directory)) {
  89. throw new \RuntimeException(
  90. $directory.' exists and is not a directory.'
  91. );
  92. }
  93. if (!@mkdir($directory, 0777, true)) {
  94. throw new \RuntimeException(
  95. $directory.' does not exist and could not be created.'
  96. );
  97. }
  98. }
  99. }
  100. /**
  101. * Copy then delete is a non-atomic version of {@link rename}.
  102. *
  103. * Some systems can't rename and also don't have proc_open,
  104. * which requires this solution.
  105. *
  106. * @param string $source
  107. * @param string $target
  108. */
  109. public function copyThenRemove($source, $target)
  110. {
  111. $it = new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS);
  112. $ri = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::SELF_FIRST);
  113. if ( !file_exists($target)) {
  114. mkdir($target, 0777, true);
  115. }
  116. foreach ($ri as $file) {
  117. $targetPath = $target . DIRECTORY_SEPARATOR . $ri->getSubPathName();
  118. if ($file->isDir()) {
  119. mkdir($targetPath);
  120. } else {
  121. copy($file->getPathname(), $targetPath);
  122. }
  123. }
  124. $this->removeDirectoryPhp($source);
  125. }
  126. public function rename($source, $target)
  127. {
  128. if (true === @rename($source, $target)) {
  129. return;
  130. }
  131. if (!function_exists('proc_open')) {
  132. return $this->copyThenRemove($source, $target);
  133. }
  134. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  135. // Try to copy & delete - this is a workaround for random "Access denied" errors.
  136. $command = sprintf('xcopy %s %s /E /I /Q', escapeshellarg($source), escapeshellarg($target));
  137. if (0 === $this->processExecutor->execute($command, $output)) {
  138. $this->remove($source);
  139. return;
  140. }
  141. return $this->copyThenRemove($source, $target);
  142. } else {
  143. // We do not use PHP's "rename" function here since it does not support
  144. // the case where $source, and $target are located on different partitions.
  145. $command = sprintf('mv %s %s', escapeshellarg($source), escapeshellarg($target));
  146. if (0 === $this->processExecutor->execute($command)) {
  147. return;
  148. }
  149. }
  150. throw new \RuntimeException(sprintf('Could not rename "%s" to "%s".', $source, $target));
  151. }
  152. /**
  153. * Returns the shortest path from $from to $to
  154. *
  155. * @param string $from
  156. * @param string $to
  157. * @param bool $directories if true, the source/target are considered to be directories
  158. * @return string
  159. */
  160. public function findShortestPath($from, $to, $directories = false)
  161. {
  162. if (!$this->isAbsolutePath($from) || !$this->isAbsolutePath($to)) {
  163. throw new \InvalidArgumentException(sprintf('$from (%s) and $to (%s) must be absolute paths.', $from, $to));
  164. }
  165. $from = lcfirst(rtrim(strtr($from, '\\', '/'), '/'));
  166. $to = lcfirst(rtrim(strtr($to, '\\', '/'), '/'));
  167. if ($directories) {
  168. $from .= '/dummy_file';
  169. }
  170. if (dirname($from) === dirname($to)) {
  171. return './'.basename($to);
  172. }
  173. $commonPath = $to;
  174. while (strpos($from, $commonPath) !== 0 && '/' !== $commonPath && !preg_match('{^[a-z]:/?$}i', $commonPath) && '.' !== $commonPath) {
  175. $commonPath = strtr(dirname($commonPath), '\\', '/');
  176. }
  177. if (0 !== strpos($from, $commonPath) || '/' === $commonPath || '.' === $commonPath) {
  178. return $to;
  179. }
  180. $commonPath = rtrim($commonPath, '/') . '/';
  181. $sourcePathDepth = substr_count(substr($from, strlen($commonPath)), '/');
  182. $commonPathCode = str_repeat('../', $sourcePathDepth);
  183. return ($commonPathCode . substr($to, strlen($commonPath))) ?: './';
  184. }
  185. /**
  186. * Returns PHP code that, when executed in $from, will return the path to $to
  187. *
  188. * @param string $from
  189. * @param string $to
  190. * @param bool $directories if true, the source/target are considered to be directories
  191. * @return string
  192. */
  193. public function findShortestPathCode($from, $to, $directories = false)
  194. {
  195. if (!$this->isAbsolutePath($from) || !$this->isAbsolutePath($to)) {
  196. throw new \InvalidArgumentException(sprintf('$from (%s) and $to (%s) must be absolute paths.', $from, $to));
  197. }
  198. $from = lcfirst(strtr($from, '\\', '/'));
  199. $to = lcfirst(strtr($to, '\\', '/'));
  200. if ($from === $to) {
  201. return $directories ? '__DIR__' : '__FILE__';
  202. }
  203. $commonPath = $to;
  204. while (strpos($from, $commonPath) !== 0 && '/' !== $commonPath && !preg_match('{^[a-z]:/?$}i', $commonPath) && '.' !== $commonPath) {
  205. $commonPath = strtr(dirname($commonPath), '\\', '/');
  206. }
  207. if (0 !== strpos($from, $commonPath) || '/' === $commonPath || '.' === $commonPath) {
  208. return var_export($to, true);
  209. }
  210. $commonPath = rtrim($commonPath, '/') . '/';
  211. if (strpos($to, $from.'/') === 0) {
  212. return '__DIR__ . '.var_export(substr($to, strlen($from)), true);
  213. }
  214. $sourcePathDepth = substr_count(substr($from, strlen($commonPath)), '/') + $directories;
  215. $commonPathCode = str_repeat('dirname(', $sourcePathDepth).'__DIR__'.str_repeat(')', $sourcePathDepth);
  216. $relTarget = substr($to, strlen($commonPath));
  217. return $commonPathCode . (strlen($relTarget) ? '.' . var_export('/' . $relTarget, true) : '');
  218. }
  219. /**
  220. * Checks if the given path is absolute
  221. *
  222. * @param string $path
  223. * @return bool
  224. */
  225. public function isAbsolutePath($path)
  226. {
  227. return substr($path, 0, 1) === '/' || substr($path, 1, 1) === ':';
  228. }
  229. /**
  230. * Returns size of a file or directory specified by path. If a directory is
  231. * given, it's size will be computed recursively.
  232. *
  233. * @param string $path Path to the file or directory
  234. * @return int
  235. */
  236. public function size($path)
  237. {
  238. if (!file_exists($path)) {
  239. throw new \RuntimeException("$path does not exist.");
  240. }
  241. if (is_dir($path)) {
  242. return $this->directorySize($path);
  243. }
  244. return filesize($path);
  245. }
  246. protected function directorySize($directory)
  247. {
  248. $it = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS);
  249. $ri = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
  250. $size = 0;
  251. foreach ($ri as $file) {
  252. if ($file->isFile()) {
  253. $size += $file->getSize();
  254. }
  255. }
  256. return $size;
  257. }
  258. protected function getProcess()
  259. {
  260. return new ProcessExecutor;
  261. }
  262. }