PageRenderTime 28ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Symfony/Component/Filesystem/Filesystem.php

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