Filesystem.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  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\FileNotFoundException;
  12. use Symfony\Component\Filesystem\Exception\IOException;
  13. /**
  14. * Provides basic utility to manipulate the file system.
  15. *
  16. * @author Fabien Potencier <fabien@symfony.com>
  17. */
  18. class Filesystem
  19. {
  20. private static $lastError;
  21. /**
  22. * Copies a file.
  23. *
  24. * If the target file is older than the origin file, it's always overwritten.
  25. * If the target file is newer, it is overwritten only when the
  26. * $overwriteNewerFiles option is set to true.
  27. *
  28. * @param string $originFile The original filename
  29. * @param string $targetFile The target filename
  30. * @param bool $overwriteNewerFiles If true, target files newer than origin files are overwritten
  31. *
  32. * @throws FileNotFoundException When originFile doesn't exist
  33. * @throws IOException When copy fails
  34. */
  35. public function copy($originFile, $targetFile, $overwriteNewerFiles = false)
  36. {
  37. $originIsLocal = stream_is_local($originFile) || 0 === stripos($originFile, 'file://');
  38. if ($originIsLocal && !is_file($originFile)) {
  39. throw new FileNotFoundException(sprintf('Failed to copy "%s" because file does not exist.', $originFile), 0, null, $originFile);
  40. }
  41. $this->mkdir(\dirname($targetFile));
  42. $doCopy = true;
  43. if (!$overwriteNewerFiles && null === parse_url($originFile, PHP_URL_HOST) && is_file($targetFile)) {
  44. $doCopy = filemtime($originFile) > filemtime($targetFile);
  45. }
  46. if ($doCopy) {
  47. // https://bugs.php.net/bug.php?id=64634
  48. if (false === $source = @fopen($originFile, 'r')) {
  49. throw new IOException(sprintf('Failed to copy "%s" to "%s" because source file could not be opened for reading.', $originFile, $targetFile), 0, null, $originFile);
  50. }
  51. // Stream context created to allow files overwrite when using FTP stream wrapper - disabled by default
  52. if (false === $target = @fopen($targetFile, 'w', null, stream_context_create(array('ftp' => array('overwrite' => true))))) {
  53. throw new IOException(sprintf('Failed to copy "%s" to "%s" because target file could not be opened for writing.', $originFile, $targetFile), 0, null, $originFile);
  54. }
  55. $bytesCopied = stream_copy_to_stream($source, $target);
  56. fclose($source);
  57. fclose($target);
  58. unset($source, $target);
  59. if (!is_file($targetFile)) {
  60. throw new IOException(sprintf('Failed to copy "%s" to "%s".', $originFile, $targetFile), 0, null, $originFile);
  61. }
  62. if ($originIsLocal) {
  63. // Like `cp`, preserve executable permission bits
  64. @chmod($targetFile, fileperms($targetFile) | (fileperms($originFile) & 0111));
  65. if ($bytesCopied !== $bytesOrigin = filesize($originFile)) {
  66. throw new IOException(sprintf('Failed to copy the whole content of "%s" to "%s" (%g of %g bytes copied).', $originFile, $targetFile, $bytesCopied, $bytesOrigin), 0, null, $originFile);
  67. }
  68. }
  69. }
  70. }
  71. /**
  72. * Creates a directory recursively.
  73. *
  74. * @param string|iterable $dirs The directory path
  75. * @param int $mode The directory mode
  76. *
  77. * @throws IOException On any directory creation failure
  78. */
  79. public function mkdir($dirs, $mode = 0777)
  80. {
  81. foreach ($this->toIterator($dirs) as $dir) {
  82. if (is_dir($dir)) {
  83. continue;
  84. }
  85. if (!self::box('mkdir', $dir, $mode, true)) {
  86. if (!is_dir($dir)) {
  87. // The directory was not created by a concurrent process. Let's throw an exception with a developer friendly error message if we have one
  88. if (self::$lastError) {
  89. throw new IOException(sprintf('Failed to create "%s": %s.', $dir, self::$lastError), 0, null, $dir);
  90. }
  91. throw new IOException(sprintf('Failed to create "%s"', $dir), 0, null, $dir);
  92. }
  93. }
  94. }
  95. }
  96. /**
  97. * Checks the existence of files or directories.
  98. *
  99. * @param string|iterable $files A filename, an array of files, or a \Traversable instance to check
  100. *
  101. * @return bool true if the file exists, false otherwise
  102. */
  103. public function exists($files)
  104. {
  105. $maxPathLength = PHP_MAXPATHLEN - 2;
  106. foreach ($this->toIterator($files) as $file) {
  107. if (\strlen($file) > $maxPathLength) {
  108. throw new IOException(sprintf('Could not check if file exist because path length exceeds %d characters.', $maxPathLength), 0, null, $file);
  109. }
  110. if (!file_exists($file)) {
  111. return false;
  112. }
  113. }
  114. return true;
  115. }
  116. /**
  117. * Sets access and modification time of file.
  118. *
  119. * @param string|iterable $files A filename, an array of files, or a \Traversable instance to create
  120. * @param int $time The touch time as a Unix timestamp
  121. * @param int $atime The access time as a Unix timestamp
  122. *
  123. * @throws IOException When touch fails
  124. */
  125. public function touch($files, $time = null, $atime = null)
  126. {
  127. foreach ($this->toIterator($files) as $file) {
  128. $touch = $time ? @touch($file, $time, $atime) : @touch($file);
  129. if (true !== $touch) {
  130. throw new IOException(sprintf('Failed to touch "%s".', $file), 0, null, $file);
  131. }
  132. }
  133. }
  134. /**
  135. * Removes files or directories.
  136. *
  137. * @param string|iterable $files A filename, an array of files, or a \Traversable instance to remove
  138. *
  139. * @throws IOException When removal fails
  140. */
  141. public function remove($files)
  142. {
  143. if ($files instanceof \Traversable) {
  144. $files = iterator_to_array($files, false);
  145. } elseif (!\is_array($files)) {
  146. $files = array($files);
  147. }
  148. $files = array_reverse($files);
  149. foreach ($files as $file) {
  150. if (is_link($file)) {
  151. // See https://bugs.php.net/52176
  152. if (!(self::box('unlink', $file) || '\\' !== \DIRECTORY_SEPARATOR || self::box('rmdir', $file)) && file_exists($file)) {
  153. throw new IOException(sprintf('Failed to remove symlink "%s": %s.', $file, self::$lastError));
  154. }
  155. } elseif (is_dir($file)) {
  156. $this->remove(new \FilesystemIterator($file, \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS));
  157. if (!self::box('rmdir', $file) && file_exists($file)) {
  158. throw new IOException(sprintf('Failed to remove directory "%s": %s.', $file, self::$lastError));
  159. }
  160. } elseif (!self::box('unlink', $file) && file_exists($file)) {
  161. throw new IOException(sprintf('Failed to remove file "%s": %s.', $file, self::$lastError));
  162. }
  163. }
  164. }
  165. /**
  166. * Change mode for an array of files or directories.
  167. *
  168. * @param string|iterable $files A filename, an array of files, or a \Traversable instance to change mode
  169. * @param int $mode The new mode (octal)
  170. * @param int $umask The mode mask (octal)
  171. * @param bool $recursive Whether change the mod recursively or not
  172. *
  173. * @throws IOException When the change fail
  174. */
  175. public function chmod($files, $mode, $umask = 0000, $recursive = false)
  176. {
  177. foreach ($this->toIterator($files) as $file) {
  178. if (true !== @chmod($file, $mode & ~$umask)) {
  179. throw new IOException(sprintf('Failed to chmod file "%s".', $file), 0, null, $file);
  180. }
  181. if ($recursive && is_dir($file) && !is_link($file)) {
  182. $this->chmod(new \FilesystemIterator($file), $mode, $umask, true);
  183. }
  184. }
  185. }
  186. /**
  187. * Change the owner of an array of files or directories.
  188. *
  189. * @param string|iterable $files A filename, an array of files, or a \Traversable instance to change owner
  190. * @param string $user The new owner user name
  191. * @param bool $recursive Whether change the owner recursively or not
  192. *
  193. * @throws IOException When the change fail
  194. */
  195. public function chown($files, $user, $recursive = false)
  196. {
  197. foreach ($this->toIterator($files) as $file) {
  198. if ($recursive && is_dir($file) && !is_link($file)) {
  199. $this->chown(new \FilesystemIterator($file), $user, true);
  200. }
  201. if (is_link($file) && \function_exists('lchown')) {
  202. if (true !== @lchown($file, $user)) {
  203. throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file);
  204. }
  205. } else {
  206. if (true !== @chown($file, $user)) {
  207. throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file);
  208. }
  209. }
  210. }
  211. }
  212. /**
  213. * Change the group of an array of files or directories.
  214. *
  215. * @param string|iterable $files A filename, an array of files, or a \Traversable instance to change group
  216. * @param string $group The group name
  217. * @param bool $recursive Whether change the group recursively or not
  218. *
  219. * @throws IOException When the change fail
  220. */
  221. public function chgrp($files, $group, $recursive = false)
  222. {
  223. foreach ($this->toIterator($files) as $file) {
  224. if ($recursive && is_dir($file) && !is_link($file)) {
  225. $this->chgrp(new \FilesystemIterator($file), $group, true);
  226. }
  227. if (is_link($file) && \function_exists('lchgrp')) {
  228. if (true !== @lchgrp($file, $group) || (\defined('HHVM_VERSION') && !posix_getgrnam($group))) {
  229. throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file);
  230. }
  231. } else {
  232. if (true !== @chgrp($file, $group)) {
  233. throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file);
  234. }
  235. }
  236. }
  237. }
  238. /**
  239. * Renames a file or a directory.
  240. *
  241. * @param string $origin The origin filename or directory
  242. * @param string $target The new filename or directory
  243. * @param bool $overwrite Whether to overwrite the target if it already exists
  244. *
  245. * @throws IOException When target file or directory already exists
  246. * @throws IOException When origin cannot be renamed
  247. */
  248. public function rename($origin, $target, $overwrite = false)
  249. {
  250. // we check that target does not exist
  251. if (!$overwrite && $this->isReadable($target)) {
  252. throw new IOException(sprintf('Cannot rename because the target "%s" already exists.', $target), 0, null, $target);
  253. }
  254. if (true !== @rename($origin, $target)) {
  255. if (is_dir($origin)) {
  256. // See https://bugs.php.net/bug.php?id=54097 & http://php.net/manual/en/function.rename.php#113943
  257. $this->mirror($origin, $target, null, array('override' => $overwrite, 'delete' => $overwrite));
  258. $this->remove($origin);
  259. return;
  260. }
  261. throw new IOException(sprintf('Cannot rename "%s" to "%s".', $origin, $target), 0, null, $target);
  262. }
  263. }
  264. /**
  265. * Tells whether a file exists and is readable.
  266. *
  267. * @param string $filename Path to the file
  268. *
  269. * @return bool
  270. *
  271. * @throws IOException When windows path is longer than 258 characters
  272. */
  273. private function isReadable($filename)
  274. {
  275. $maxPathLength = PHP_MAXPATHLEN - 2;
  276. if (\strlen($filename) > $maxPathLength) {
  277. throw new IOException(sprintf('Could not check if file is readable because path length exceeds %d characters.', $maxPathLength), 0, null, $filename);
  278. }
  279. return is_readable($filename);
  280. }
  281. /**
  282. * Creates a symbolic link or copy a directory.
  283. *
  284. * @param string $originDir The origin directory path
  285. * @param string $targetDir The symbolic link name
  286. * @param bool $copyOnWindows Whether to copy files if on Windows
  287. *
  288. * @throws IOException When symlink fails
  289. */
  290. public function symlink($originDir, $targetDir, $copyOnWindows = false)
  291. {
  292. if ('\\' === \DIRECTORY_SEPARATOR) {
  293. $originDir = strtr($originDir, '/', '\\');
  294. $targetDir = strtr($targetDir, '/', '\\');
  295. if ($copyOnWindows) {
  296. $this->mirror($originDir, $targetDir);
  297. return;
  298. }
  299. }
  300. $this->mkdir(\dirname($targetDir));
  301. if (is_link($targetDir)) {
  302. if (readlink($targetDir) === $originDir) {
  303. return;
  304. }
  305. $this->remove($targetDir);
  306. }
  307. if (!self::box('symlink', $originDir, $targetDir)) {
  308. if (null !== self::$lastError) {
  309. if ('\\' === \DIRECTORY_SEPARATOR && false !== strpos(self::$lastError, 'error code(1314)')) {
  310. 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?', 0, null, $targetDir);
  311. }
  312. }
  313. throw new IOException(sprintf('Failed to create symbolic link from "%s" to "%s".', $originDir, $targetDir), 0, null, $targetDir);
  314. }
  315. }
  316. /**
  317. * Given an existing path, convert it to a path relative to a given starting path.
  318. *
  319. * @param string $endPath Absolute path of target
  320. * @param string $startPath Absolute path where traversal begins
  321. *
  322. * @return string Path of target relative to starting path
  323. */
  324. public function makePathRelative($endPath, $startPath)
  325. {
  326. // Normalize separators on Windows
  327. if ('\\' === \DIRECTORY_SEPARATOR) {
  328. $endPath = str_replace('\\', '/', $endPath);
  329. $startPath = str_replace('\\', '/', $startPath);
  330. }
  331. $stripDriveLetter = function ($path) {
  332. if (\strlen($path) > 2 && ':' === $path[1] && '/' === $path[2] && ctype_alpha($path[0])) {
  333. return substr($path, 2);
  334. }
  335. return $path;
  336. };
  337. $endPath = $stripDriveLetter($endPath);
  338. $startPath = $stripDriveLetter($startPath);
  339. // Split the paths into arrays
  340. $startPathArr = explode('/', trim($startPath, '/'));
  341. $endPathArr = explode('/', trim($endPath, '/'));
  342. $normalizePathArray = function ($pathSegments, $absolute) {
  343. $result = array();
  344. foreach ($pathSegments as $segment) {
  345. if ('..' === $segment && ($absolute || \count($result))) {
  346. array_pop($result);
  347. } elseif ('.' !== $segment) {
  348. $result[] = $segment;
  349. }
  350. }
  351. return $result;
  352. };
  353. $startPathArr = $normalizePathArray($startPathArr, static::isAbsolutePath($startPath));
  354. $endPathArr = $normalizePathArray($endPathArr, static::isAbsolutePath($endPath));
  355. // Find for which directory the common path stops
  356. $index = 0;
  357. while (isset($startPathArr[$index]) && isset($endPathArr[$index]) && $startPathArr[$index] === $endPathArr[$index]) {
  358. ++$index;
  359. }
  360. // Determine how deep the start path is relative to the common path (ie, "web/bundles" = 2 levels)
  361. if (1 === \count($startPathArr) && '' === $startPathArr[0]) {
  362. $depth = 0;
  363. } else {
  364. $depth = \count($startPathArr) - $index;
  365. }
  366. // Repeated "../" for each level need to reach the common path
  367. $traverser = str_repeat('../', $depth);
  368. $endPathRemainder = implode('/', \array_slice($endPathArr, $index));
  369. // Construct $endPath from traversing to the common path, then to the remaining $endPath
  370. $relativePath = $traverser.('' !== $endPathRemainder ? $endPathRemainder.'/' : '');
  371. return '' === $relativePath ? './' : $relativePath;
  372. }
  373. /**
  374. * Mirrors a directory to another.
  375. *
  376. * Copies files and directories from the origin directory into the target directory. By default:
  377. *
  378. * - existing files in the target directory will be overwritten, except if they are newer (see the `override` option)
  379. * - files in the target directory that do not exist in the source directory will not be deleted (see the `delete` option)
  380. *
  381. * @param string $originDir The origin directory
  382. * @param string $targetDir The target directory
  383. * @param \Traversable $iterator Iterator that filters which files and directories to copy
  384. * @param array $options An array of boolean options
  385. * Valid options are:
  386. * - $options['override'] If true, target files newer than origin files are overwritten (see copy(), defaults to false)
  387. * - $options['copy_on_windows'] Whether to copy files instead of links on Windows (see symlink(), defaults to false)
  388. * - $options['delete'] Whether to delete files that are not in the source directory (defaults to false)
  389. *
  390. * @throws IOException When file type is unknown
  391. */
  392. public function mirror($originDir, $targetDir, \Traversable $iterator = null, $options = array())
  393. {
  394. $targetDir = rtrim($targetDir, '/\\');
  395. $originDir = rtrim($originDir, '/\\');
  396. $originDirLen = \strlen($originDir);
  397. // Iterate in destination folder to remove obsolete entries
  398. if ($this->exists($targetDir) && isset($options['delete']) && $options['delete']) {
  399. $deleteIterator = $iterator;
  400. if (null === $deleteIterator) {
  401. $flags = \FilesystemIterator::SKIP_DOTS;
  402. $deleteIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($targetDir, $flags), \RecursiveIteratorIterator::CHILD_FIRST);
  403. }
  404. $targetDirLen = \strlen($targetDir);
  405. foreach ($deleteIterator as $file) {
  406. $origin = $originDir.substr($file->getPathname(), $targetDirLen);
  407. if (!$this->exists($origin)) {
  408. $this->remove($file);
  409. }
  410. }
  411. }
  412. $copyOnWindows = false;
  413. if (isset($options['copy_on_windows'])) {
  414. $copyOnWindows = $options['copy_on_windows'];
  415. }
  416. if (null === $iterator) {
  417. $flags = $copyOnWindows ? \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS : \FilesystemIterator::SKIP_DOTS;
  418. $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($originDir, $flags), \RecursiveIteratorIterator::SELF_FIRST);
  419. }
  420. if ($this->exists($originDir)) {
  421. $this->mkdir($targetDir);
  422. }
  423. foreach ($iterator as $file) {
  424. $target = $targetDir.substr($file->getPathname(), $originDirLen);
  425. if ($copyOnWindows) {
  426. if (is_file($file)) {
  427. $this->copy($file, $target, isset($options['override']) ? $options['override'] : false);
  428. } elseif (is_dir($file)) {
  429. $this->mkdir($target);
  430. } else {
  431. throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file);
  432. }
  433. } else {
  434. if (is_link($file)) {
  435. $this->symlink($file->getLinkTarget(), $target);
  436. } elseif (is_dir($file)) {
  437. $this->mkdir($target);
  438. } elseif (is_file($file)) {
  439. $this->copy($file, $target, isset($options['override']) ? $options['override'] : false);
  440. } else {
  441. throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file);
  442. }
  443. }
  444. }
  445. }
  446. /**
  447. * Returns whether the file path is an absolute path.
  448. *
  449. * @param string $file A file path
  450. *
  451. * @return bool
  452. */
  453. public function isAbsolutePath($file)
  454. {
  455. return strspn($file, '/\\', 0, 1)
  456. || (\strlen($file) > 3 && ctype_alpha($file[0])
  457. && ':' === substr($file, 1, 1)
  458. && strspn($file, '/\\', 2, 1)
  459. )
  460. || null !== parse_url($file, PHP_URL_SCHEME)
  461. ;
  462. }
  463. /**
  464. * Creates a temporary file with support for custom stream wrappers.
  465. *
  466. * @param string $dir The directory where the temporary filename will be created
  467. * @param string $prefix The prefix of the generated temporary filename
  468. * Note: Windows uses only the first three characters of prefix
  469. *
  470. * @return string The new temporary filename (with path), or throw an exception on failure
  471. */
  472. public function tempnam($dir, $prefix)
  473. {
  474. list($scheme, $hierarchy) = $this->getSchemeAndHierarchy($dir);
  475. // If no scheme or scheme is "file" or "gs" (Google Cloud) create temp file in local filesystem
  476. if (null === $scheme || 'file' === $scheme || 'gs' === $scheme) {
  477. $tmpFile = @tempnam($hierarchy, $prefix);
  478. // If tempnam failed or no scheme return the filename otherwise prepend the scheme
  479. if (false !== $tmpFile) {
  480. if (null !== $scheme && 'gs' !== $scheme) {
  481. return $scheme.'://'.$tmpFile;
  482. }
  483. return $tmpFile;
  484. }
  485. throw new IOException('A temporary file could not be created.');
  486. }
  487. // Loop until we create a valid temp file or have reached 10 attempts
  488. for ($i = 0; $i < 10; ++$i) {
  489. // Create a unique filename
  490. $tmpFile = $dir.'/'.$prefix.uniqid(mt_rand(), true);
  491. // Use fopen instead of file_exists as some streams do not support stat
  492. // Use mode 'x+' to atomically check existence and create to avoid a TOCTOU vulnerability
  493. $handle = @fopen($tmpFile, 'x+');
  494. // If unsuccessful restart the loop
  495. if (false === $handle) {
  496. continue;
  497. }
  498. // Close the file if it was successfully opened
  499. @fclose($handle);
  500. return $tmpFile;
  501. }
  502. throw new IOException('A temporary file could not be created.');
  503. }
  504. /**
  505. * Atomically dumps content into a file.
  506. *
  507. * @param string $filename The file to be written to
  508. * @param string $content The data to write into the file
  509. * @param int|null $mode The file mode (octal). If null, file permissions are not modified
  510. * Deprecated since version 2.3.12, to be removed in 3.0.
  511. *
  512. * @throws IOException if the file cannot be written to
  513. */
  514. public function dumpFile($filename, $content, $mode = 0666)
  515. {
  516. $dir = \dirname($filename);
  517. if (!is_dir($dir)) {
  518. $this->mkdir($dir);
  519. }
  520. if (!is_writable($dir)) {
  521. throw new IOException(sprintf('Unable to write to the "%s" directory.', $dir), 0, null, $dir);
  522. }
  523. $tmpFile = $this->tempnam($dir, basename($filename));
  524. if (false === @file_put_contents($tmpFile, $content)) {
  525. throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename);
  526. }
  527. if (null !== $mode) {
  528. if (\func_num_args() > 2) {
  529. @trigger_error('Support for modifying file permissions is deprecated since Symfony 2.3.12 and will be removed in 3.0.', E_USER_DEPRECATED);
  530. }
  531. $this->chmod($tmpFile, $mode);
  532. } elseif (file_exists($filename)) {
  533. @chmod($tmpFile, fileperms($filename));
  534. }
  535. $this->rename($tmpFile, $filename, true);
  536. }
  537. /**
  538. * @param mixed $files
  539. *
  540. * @return \Traversable
  541. */
  542. private function toIterator($files)
  543. {
  544. if (!$files instanceof \Traversable) {
  545. $files = new \ArrayObject(\is_array($files) ? $files : array($files));
  546. }
  547. return $files;
  548. }
  549. /**
  550. * Gets a 2-tuple of scheme (may be null) and hierarchical part of a filename (e.g. file:///tmp -> array(file, tmp)).
  551. *
  552. * @param string $filename The filename to be parsed
  553. *
  554. * @return array The filename scheme and hierarchical part
  555. */
  556. private function getSchemeAndHierarchy($filename)
  557. {
  558. $components = explode('://', $filename, 2);
  559. return 2 === \count($components) ? array($components[0], $components[1]) : array(null, $components[0]);
  560. }
  561. private static function box($func)
  562. {
  563. self::$lastError = null;
  564. \set_error_handler(__CLASS__.'::handleError');
  565. try {
  566. $result = \call_user_func_array($func, \array_slice(\func_get_args(), 1));
  567. \restore_error_handler();
  568. return $result;
  569. } catch (\Throwable $e) {
  570. } catch (\Exception $e) {
  571. }
  572. \restore_error_handler();
  573. throw $e;
  574. }
  575. /**
  576. * @internal
  577. */
  578. public static function handleError($type, $msg)
  579. {
  580. self::$lastError = $msg;
  581. }
  582. }