FileHelper.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Mtf\Util\Filesystem;
  7. /**
  8. * Filesystem helper.
  9. */
  10. class FileHelper
  11. {
  12. /**
  13. * Normalizes a file/directory path.
  14. *
  15. * @param string $path
  16. * @param string $ds
  17. * @return string
  18. */
  19. public function normalizePath($path, $ds = DIRECTORY_SEPARATOR)
  20. {
  21. $path = rtrim(strtr($path, '/\\', $ds . $ds), $ds);
  22. if (strpos($ds . $path, "{$ds}.") === false && strpos($path, "{$ds}{$ds}") === false) {
  23. return $path;
  24. }
  25. return $this->realpath($ds, $path);
  26. }
  27. /**
  28. * Returns canonicalized pathname.
  29. *
  30. * @param string $ds
  31. * @param string $path
  32. * @return string
  33. */
  34. private function realpath($ds, $path)
  35. {
  36. $parts = [];
  37. foreach (explode($ds, $path) as $part) {
  38. if ($part === '..' && !empty($parts) && end($parts) !== '..') {
  39. array_pop($parts);
  40. } elseif ($part === '.' || $part === '' && !empty($parts)) {
  41. continue;
  42. } else {
  43. $parts[] = $part;
  44. }
  45. }
  46. $path = implode($ds, $parts);
  47. return $path === '' ? '.' : $path;
  48. }
  49. /**
  50. * Creates a new directory.
  51. *
  52. * @param string $path
  53. * @param int $mode
  54. * @param bool $recursive
  55. * @return bool
  56. * @throws \Exception
  57. */
  58. public function createDirectory($path, $mode = 0775, $recursive = true)
  59. {
  60. if (is_dir($path)) {
  61. return true;
  62. }
  63. $parentDir = dirname($path);
  64. if ($recursive && !is_dir($parentDir) && $parentDir !== $path) {
  65. $this->createDirectory($parentDir, $mode, true);
  66. }
  67. try {
  68. if (!mkdir($path, $mode)) {
  69. return false;
  70. }
  71. } catch (\Exception $e) {
  72. if (!is_dir($path)) {
  73. throw new \Exception("Failed to create directory \"$path\"");
  74. }
  75. }
  76. try {
  77. return chmod($path, $mode);
  78. } catch (\Exception $e) {
  79. throw new \Exception("Failed to change permissions for directory \"$path\"");
  80. }
  81. }
  82. /**
  83. * Create a new file with content.
  84. *
  85. * @param string $filename
  86. * @param string $content
  87. * @return bool
  88. */
  89. public function createFile($filename, $content)
  90. {
  91. return file_put_contents($filename, $content) !== false;
  92. }
  93. }