PageRenderTime 43ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/src/Composer/Util/Filesystem.php

https://github.com/theshadow/composer
PHP | 310 lines | 202 code | 42 blank | 66 comment | 37 complexity | 09f5bcff0c91441b18339b1e97e4fca6 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) === 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 dont 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)) {
  138. $this->remove($source);
  139. return;
  140. }
  141. } else {
  142. // We do not use PHP's "rename" function here since it does not support
  143. // the case where $source, and $target are located on different partitions.
  144. $command = sprintf('mv %s %s', escapeshellarg($source), escapeshellarg($target));
  145. if (0 === $this->processExecutor->execute($command)) {
  146. return;
  147. }
  148. }
  149. throw new \RuntimeException(sprintf('Could not rename "%s" to "%s".', $source, $target));
  150. }
  151. /**
  152. * Returns the shortest path from $from to $to
  153. *
  154. * @param string $from
  155. * @param string $to
  156. * @param bool $directories if true, the source/target are considered to be directories
  157. * @return string
  158. */
  159. public function findShortestPath($from, $to, $directories = false)
  160. {
  161. if (!$this->isAbsolutePath($from) || !$this->isAbsolutePath($to)) {
  162. throw new \InvalidArgumentException(sprintf('$from (%s) and $to (%s) must be absolute paths.', $from, $to));
  163. }
  164. $from = lcfirst(rtrim(strtr($from, '\\', '/'), '/'));
  165. $to = lcfirst(rtrim(strtr($to, '\\', '/'), '/'));
  166. if ($directories) {
  167. $from .= '/dummy_file';
  168. }
  169. if (dirname($from) === dirname($to)) {
  170. return './'.basename($to);
  171. }
  172. $commonPath = $to;
  173. while (strpos($from, $commonPath) !== 0 && '/' !== $commonPath && !preg_match('{^[a-z]:/?$}i', $commonPath) && '.' !== $commonPath) {
  174. $commonPath = strtr(dirname($commonPath), '\\', '/');
  175. }
  176. if (0 !== strpos($from, $commonPath) || '/' === $commonPath || '.' === $commonPath) {
  177. return $to;
  178. }
  179. $commonPath = rtrim($commonPath, '/') . '/';
  180. $sourcePathDepth = substr_count(substr($from, strlen($commonPath)), '/');
  181. $commonPathCode = str_repeat('../', $sourcePathDepth);
  182. return ($commonPathCode . substr($to, strlen($commonPath))) ?: './';
  183. }
  184. /**
  185. * Returns PHP code that, when executed in $from, will return the path to $to
  186. *
  187. * @param string $from
  188. * @param string $to
  189. * @param bool $directories if true, the source/target are considered to be directories
  190. * @return string
  191. */
  192. public function findShortestPathCode($from, $to, $directories = false)
  193. {
  194. if (!$this->isAbsolutePath($from) || !$this->isAbsolutePath($to)) {
  195. throw new \InvalidArgumentException(sprintf('$from (%s) and $to (%s) must be absolute paths.', $from, $to));
  196. }
  197. $from = lcfirst(strtr($from, '\\', '/'));
  198. $to = lcfirst(strtr($to, '\\', '/'));
  199. if ($from === $to) {
  200. return $directories ? '__DIR__' : '__FILE__';
  201. }
  202. $commonPath = $to;
  203. while (strpos($from, $commonPath) !== 0 && '/' !== $commonPath && !preg_match('{^[a-z]:/?$}i', $commonPath) && '.' !== $commonPath) {
  204. $commonPath = strtr(dirname($commonPath), '\\', '/');
  205. }
  206. if (0 !== strpos($from, $commonPath) || '/' === $commonPath || '.' === $commonPath) {
  207. return var_export($to, true);
  208. }
  209. $commonPath = rtrim($commonPath, '/') . '/';
  210. if (strpos($to, $from.'/') === 0) {
  211. return '__DIR__ . '.var_export(substr($to, strlen($from)), true);
  212. }
  213. $sourcePathDepth = substr_count(substr($from, strlen($commonPath)), '/') + $directories;
  214. $commonPathCode = str_repeat('dirname(', $sourcePathDepth).'__DIR__'.str_repeat(')', $sourcePathDepth);
  215. $relTarget = substr($to, strlen($commonPath));
  216. return $commonPathCode . (strlen($relTarget) ? '.' . var_export('/' . $relTarget, true) : '');
  217. }
  218. /**
  219. * Checks if the given path is absolute
  220. *
  221. * @param string $path
  222. * @return bool
  223. */
  224. public function isAbsolutePath($path)
  225. {
  226. return substr($path, 0, 1) === '/' || substr($path, 1, 1) === ':';
  227. }
  228. /**
  229. * Returns size of a file or directory specified by path. If a directory is
  230. * given, it's size will be computed recursively.
  231. *
  232. * @param string $path Path to the file or directory
  233. * @return int
  234. */
  235. public function size($path)
  236. {
  237. if (!file_exists($path)) {
  238. throw new \RuntimeException("$path does not exist.");
  239. }
  240. if (is_dir($path)) {
  241. return $this->directorySize($path);
  242. }
  243. return filesize($path);
  244. }
  245. protected function directorySize($directory)
  246. {
  247. $it = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS);
  248. $ri = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
  249. $size = 0;
  250. foreach ($ri as $file) {
  251. if ($file->isFile()) {
  252. $size += $file->getSize();
  253. }
  254. }
  255. return $size;
  256. }
  257. protected function getProcess()
  258. {
  259. return new ProcessExecutor;
  260. }
  261. }