PageRenderTime 50ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/symfony/symfony/src/Symfony/Component/Filesystem/Filesystem.php

https://gitlab.com/Jlb/jlbdigitalserviceswebsiteproject
PHP | 485 lines | 275 code | 50 blank | 160 comment | 84 complexity | 68840af19acccd5dd0e7f9028b55936f MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Filesystem;
  11. use Symfony\Component\Filesystem\Exception\IOException;
  12. use Symfony\Component\Filesystem\Exception\FileNotFoundException;
  13. /**
  14. * Provides basic utility to manipulate the file system.
  15. *
  16. * @author Fabien Potencier <fabien@symfony.com>
  17. */
  18. class Filesystem
  19. {
  20. /**
  21. * Copies a file.
  22. *
  23. * This method only copies the file if the origin file is newer than the target file.
  24. *
  25. * By default, if the target already exists, it is not overridden.
  26. *
  27. * @param string $originFile The original filename
  28. * @param string $targetFile The target filename
  29. * @param bool $override Whether to override an existing file or not
  30. *
  31. * @throws FileNotFoundException When originFile doesn't exist
  32. * @throws IOException When copy fails
  33. */
  34. public function copy($originFile, $targetFile, $override = false)
  35. {
  36. if (stream_is_local($originFile) && !is_file($originFile)) {
  37. throw new FileNotFoundException(sprintf('Failed to copy "%s" because file does not exist.', $originFile), 0, null, $originFile);
  38. }
  39. $this->mkdir(dirname($targetFile));
  40. if (!$override && is_file($targetFile) && null === parse_url($originFile, PHP_URL_HOST)) {
  41. $doCopy = filemtime($originFile) > filemtime($targetFile);
  42. } else {
  43. $doCopy = true;
  44. }
  45. if ($doCopy) {
  46. // https://bugs.php.net/bug.php?id=64634
  47. $source = fopen($originFile, 'r');
  48. // Stream context created to allow files overwrite when using FTP stream wrapper - disabled by default
  49. $target = fopen($targetFile, 'w', null, stream_context_create(array('ftp' => array('overwrite' => true))));
  50. stream_copy_to_stream($source, $target);
  51. fclose($source);
  52. fclose($target);
  53. unset($source, $target);
  54. if (!is_file($targetFile)) {
  55. throw new IOException(sprintf('Failed to copy "%s" to "%s".', $originFile, $targetFile), 0, null, $originFile);
  56. }
  57. }
  58. }
  59. /**
  60. * Creates a directory recursively.
  61. *
  62. * @param string|array|\Traversable $dirs The directory path
  63. * @param int $mode The directory mode
  64. *
  65. * @throws IOException On any directory creation failure
  66. */
  67. public function mkdir($dirs, $mode = 0777)
  68. {
  69. foreach ($this->toIterator($dirs) as $dir) {
  70. if (is_dir($dir)) {
  71. continue;
  72. }
  73. if (true !== @mkdir($dir, $mode, true)) {
  74. $error = error_get_last();
  75. if (!is_dir($dir)) {
  76. // The directory was not created by a concurrent process. Let's throw an exception with a developer friendly error message if we have one
  77. if ($error) {
  78. throw new IOException(sprintf('Failed to create "%s": %s.', $dir, $error['message']), 0, null, $dir);
  79. }
  80. throw new IOException(sprintf('Failed to create "%s"', $dir), 0, null, $dir);
  81. }
  82. }
  83. }
  84. }
  85. /**
  86. * Checks the existence of files or directories.
  87. *
  88. * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to check
  89. *
  90. * @return bool true if the file exists, false otherwise
  91. */
  92. public function exists($files)
  93. {
  94. foreach ($this->toIterator($files) as $file) {
  95. if (!file_exists($file)) {
  96. return false;
  97. }
  98. }
  99. return true;
  100. }
  101. /**
  102. * Sets access and modification time of file.
  103. *
  104. * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to create
  105. * @param int $time The touch time as a Unix timestamp
  106. * @param int $atime The access time as a Unix timestamp
  107. *
  108. * @throws IOException When touch fails
  109. */
  110. public function touch($files, $time = null, $atime = null)
  111. {
  112. foreach ($this->toIterator($files) as $file) {
  113. $touch = $time ? @touch($file, $time, $atime) : @touch($file);
  114. if (true !== $touch) {
  115. throw new IOException(sprintf('Failed to touch "%s".', $file), 0, null, $file);
  116. }
  117. }
  118. }
  119. /**
  120. * Removes files or directories.
  121. *
  122. * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to remove
  123. *
  124. * @throws IOException When removal fails
  125. */
  126. public function remove($files)
  127. {
  128. $files = iterator_to_array($this->toIterator($files));
  129. $files = array_reverse($files);
  130. foreach ($files as $file) {
  131. if (!file_exists($file) && !is_link($file)) {
  132. continue;
  133. }
  134. if (is_dir($file) && !is_link($file)) {
  135. $this->remove(new \FilesystemIterator($file));
  136. if (true !== @rmdir($file)) {
  137. throw new IOException(sprintf('Failed to remove directory "%s".', $file), 0, null, $file);
  138. }
  139. } else {
  140. // https://bugs.php.net/bug.php?id=52176
  141. if (defined('PHP_WINDOWS_VERSION_MAJOR') && is_dir($file)) {
  142. if (true !== @rmdir($file)) {
  143. throw new IOException(sprintf('Failed to remove file "%s".', $file), 0, null, $file);
  144. }
  145. } else {
  146. if (true !== @unlink($file)) {
  147. throw new IOException(sprintf('Failed to remove file "%s".', $file), 0, null, $file);
  148. }
  149. }
  150. }
  151. }
  152. }
  153. /**
  154. * Change mode for an array of files or directories.
  155. *
  156. * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to change mode
  157. * @param int $mode The new mode (octal)
  158. * @param int $umask The mode mask (octal)
  159. * @param bool $recursive Whether change the mod recursively or not
  160. *
  161. * @throws IOException When the change fail
  162. */
  163. public function chmod($files, $mode, $umask = 0000, $recursive = false)
  164. {
  165. foreach ($this->toIterator($files) as $file) {
  166. if ($recursive && is_dir($file) && !is_link($file)) {
  167. $this->chmod(new \FilesystemIterator($file), $mode, $umask, true);
  168. }
  169. if (true !== @chmod($file, $mode & ~$umask)) {
  170. throw new IOException(sprintf('Failed to chmod file "%s".', $file), 0, null, $file);
  171. }
  172. }
  173. }
  174. /**
  175. * Change the owner of an array of files or directories
  176. *
  177. * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to change owner
  178. * @param string $user The new owner user name
  179. * @param bool $recursive Whether change the owner recursively or not
  180. *
  181. * @throws IOException When the change fail
  182. */
  183. public function chown($files, $user, $recursive = false)
  184. {
  185. foreach ($this->toIterator($files) as $file) {
  186. if ($recursive && is_dir($file) && !is_link($file)) {
  187. $this->chown(new \FilesystemIterator($file), $user, true);
  188. }
  189. if (is_link($file) && function_exists('lchown')) {
  190. if (true !== @lchown($file, $user)) {
  191. throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file);
  192. }
  193. } else {
  194. if (true !== @chown($file, $user)) {
  195. throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file);
  196. }
  197. }
  198. }
  199. }
  200. /**
  201. * Change the group of an array of files or directories
  202. *
  203. * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to change group
  204. * @param string $group The group name
  205. * @param bool $recursive Whether change the group recursively or not
  206. *
  207. * @throws IOException When the change fail
  208. */
  209. public function chgrp($files, $group, $recursive = false)
  210. {
  211. foreach ($this->toIterator($files) as $file) {
  212. if ($recursive && is_dir($file) && !is_link($file)) {
  213. $this->chgrp(new \FilesystemIterator($file), $group, true);
  214. }
  215. if (is_link($file) && function_exists('lchgrp')) {
  216. if (true !== @lchgrp($file, $group)) {
  217. throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file);
  218. }
  219. } else {
  220. if (true !== @chgrp($file, $group)) {
  221. throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file);
  222. }
  223. }
  224. }
  225. }
  226. /**
  227. * Renames a file or a directory.
  228. *
  229. * @param string $origin The origin filename or directory
  230. * @param string $target The new filename or directory
  231. * @param bool $overwrite Whether to overwrite the target if it already exists
  232. *
  233. * @throws IOException When target file or directory already exists
  234. * @throws IOException When origin cannot be renamed
  235. */
  236. public function rename($origin, $target, $overwrite = false)
  237. {
  238. // we check that target does not exist
  239. if (!$overwrite && is_readable($target)) {
  240. throw new IOException(sprintf('Cannot rename because the target "%s" already exists.', $target), 0, null, $target);
  241. }
  242. if (true !== @rename($origin, $target)) {
  243. throw new IOException(sprintf('Cannot rename "%s" to "%s".', $origin, $target), 0, null, $target);
  244. }
  245. }
  246. /**
  247. * Creates a symbolic link or copy a directory.
  248. *
  249. * @param string $originDir The origin directory path
  250. * @param string $targetDir The symbolic link name
  251. * @param bool $copyOnWindows Whether to copy files if on Windows
  252. *
  253. * @throws IOException When symlink fails
  254. */
  255. public function symlink($originDir, $targetDir, $copyOnWindows = false)
  256. {
  257. if (!function_exists('symlink') && $copyOnWindows) {
  258. $this->mirror($originDir, $targetDir);
  259. return;
  260. }
  261. $this->mkdir(dirname($targetDir));
  262. $ok = false;
  263. if (is_link($targetDir)) {
  264. if (readlink($targetDir) != $originDir) {
  265. $this->remove($targetDir);
  266. } else {
  267. $ok = true;
  268. }
  269. }
  270. if (!$ok) {
  271. if (true !== @symlink($originDir, $targetDir)) {
  272. $report = error_get_last();
  273. if (is_array($report)) {
  274. if (defined('PHP_WINDOWS_VERSION_MAJOR') && false !== strpos($report['message'], 'error code(1314)')) {
  275. throw new IOException('Unable to create symlink due to error code 1314: \'A required privilege is not held by the client\'. Do you have the required Administrator-rights?');
  276. }
  277. }
  278. throw new IOException(sprintf('Failed to create symbolic link from "%s" to "%s".', $originDir, $targetDir), 0, null, $targetDir);
  279. }
  280. }
  281. }
  282. /**
  283. * Given an existing path, convert it to a path relative to a given starting path
  284. *
  285. * @param string $endPath Absolute path of target
  286. * @param string $startPath Absolute path where traversal begins
  287. *
  288. * @return string Path of target relative to starting path
  289. */
  290. public function makePathRelative($endPath, $startPath)
  291. {
  292. // Normalize separators on Windows
  293. if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
  294. $endPath = strtr($endPath, '\\', '/');
  295. $startPath = strtr($startPath, '\\', '/');
  296. }
  297. // Split the paths into arrays
  298. $startPathArr = explode('/', trim($startPath, '/'));
  299. $endPathArr = explode('/', trim($endPath, '/'));
  300. // Find for which directory the common path stops
  301. $index = 0;
  302. while (isset($startPathArr[$index]) && isset($endPathArr[$index]) && $startPathArr[$index] === $endPathArr[$index]) {
  303. $index++;
  304. }
  305. // Determine how deep the start path is relative to the common path (ie, "web/bundles" = 2 levels)
  306. $depth = count($startPathArr) - $index;
  307. // Repeated "../" for each level need to reach the common path
  308. $traverser = str_repeat('../', $depth);
  309. $endPathRemainder = implode('/', array_slice($endPathArr, $index));
  310. // Construct $endPath from traversing to the common path, then to the remaining $endPath
  311. $relativePath = $traverser.(strlen($endPathRemainder) > 0 ? $endPathRemainder.'/' : '');
  312. return (strlen($relativePath) === 0) ? './' : $relativePath;
  313. }
  314. /**
  315. * Mirrors a directory to another.
  316. *
  317. * @param string $originDir The origin directory
  318. * @param string $targetDir The target directory
  319. * @param \Traversable $iterator A Traversable instance
  320. * @param array $options An array of boolean options
  321. * Valid options are:
  322. * - $options['override'] Whether to override an existing file on copy or not (see copy())
  323. * - $options['copy_on_windows'] Whether to copy files instead of links on Windows (see symlink())
  324. * - $options['delete'] Whether to delete files that are not in the source directory (defaults to false)
  325. *
  326. * @throws IOException When file type is unknown
  327. */
  328. public function mirror($originDir, $targetDir, \Traversable $iterator = null, $options = array())
  329. {
  330. $targetDir = rtrim($targetDir, '/\\');
  331. $originDir = rtrim($originDir, '/\\');
  332. // Iterate in destination folder to remove obsolete entries
  333. if ($this->exists($targetDir) && isset($options['delete']) && $options['delete']) {
  334. $deleteIterator = $iterator;
  335. if (null === $deleteIterator) {
  336. $flags = \FilesystemIterator::SKIP_DOTS;
  337. $deleteIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($targetDir, $flags), \RecursiveIteratorIterator::CHILD_FIRST);
  338. }
  339. foreach ($deleteIterator as $file) {
  340. $origin = str_replace($targetDir, $originDir, $file->getPathname());
  341. if (!$this->exists($origin)) {
  342. $this->remove($file);
  343. }
  344. }
  345. }
  346. $copyOnWindows = false;
  347. if (isset($options['copy_on_windows']) && !function_exists('symlink')) {
  348. $copyOnWindows = $options['copy_on_windows'];
  349. }
  350. if (null === $iterator) {
  351. $flags = $copyOnWindows ? \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS : \FilesystemIterator::SKIP_DOTS;
  352. $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($originDir, $flags), \RecursiveIteratorIterator::SELF_FIRST);
  353. }
  354. foreach ($iterator as $file) {
  355. $target = str_replace($originDir, $targetDir, $file->getPathname());
  356. if ($copyOnWindows) {
  357. if (is_link($file) || is_file($file)) {
  358. $this->copy($file, $target, isset($options['override']) ? $options['override'] : false);
  359. } elseif (is_dir($file)) {
  360. $this->mkdir($target);
  361. } else {
  362. throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file);
  363. }
  364. } else {
  365. if (is_link($file)) {
  366. $this->symlink($file->getLinkTarget(), $target);
  367. } elseif (is_dir($file)) {
  368. $this->mkdir($target);
  369. } elseif (is_file($file)) {
  370. $this->copy($file, $target, isset($options['override']) ? $options['override'] : false);
  371. } else {
  372. throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file);
  373. }
  374. }
  375. }
  376. }
  377. /**
  378. * Returns whether the file path is an absolute path.
  379. *
  380. * @param string $file A file path
  381. *
  382. * @return bool
  383. */
  384. public function isAbsolutePath($file)
  385. {
  386. if (strspn($file, '/\\', 0, 1)
  387. || (strlen($file) > 3 && ctype_alpha($file[0])
  388. && substr($file, 1, 1) === ':'
  389. && (strspn($file, '/\\', 2, 1))
  390. )
  391. || null !== parse_url($file, PHP_URL_SCHEME)
  392. ) {
  393. return true;
  394. }
  395. return false;
  396. }
  397. /**
  398. * Atomically dumps content into a file.
  399. *
  400. * @param string $filename The file to be written to.
  401. * @param string $content The data to write into the file.
  402. * @param null|int $mode The file mode (octal). If null, file permissions are not modified
  403. * Deprecated since version 2.3.12, to be removed in 3.0.
  404. * @throws IOException If the file cannot be written to.
  405. */
  406. public function dumpFile($filename, $content, $mode = 0666)
  407. {
  408. $dir = dirname($filename);
  409. if (!is_dir($dir)) {
  410. $this->mkdir($dir);
  411. } elseif (!is_writable($dir)) {
  412. throw new IOException(sprintf('Unable to write to the "%s" directory.', $dir), 0, null, $dir);
  413. }
  414. $tmpFile = tempnam($dir, basename($filename));
  415. if (false === @file_put_contents($tmpFile, $content)) {
  416. throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename);
  417. }
  418. $this->rename($tmpFile, $filename, true);
  419. if (null !== $mode) {
  420. $this->chmod($filename, $mode);
  421. }
  422. }
  423. /**
  424. * @param mixed $files
  425. *
  426. * @return \Traversable
  427. */
  428. private function toIterator($files)
  429. {
  430. if (!$files instanceof \Traversable) {
  431. $files = new \ArrayObject(is_array($files) ? $files : array($files));
  432. }
  433. return $files;
  434. }
  435. }