1
0

PathHelper.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Files\Utils;
  8. class PathHelper {
  9. /**
  10. * Make a path relative to a root path, or return null if the path is outside the root
  11. *
  12. * @param string $root
  13. * @param string $path
  14. * @return ?string
  15. */
  16. public static function getRelativePath(string $root, string $path) {
  17. if ($root === '' or $root === '/') {
  18. return self::normalizePath($path);
  19. }
  20. if ($path === $root) {
  21. return '/';
  22. } elseif (!str_starts_with($path, $root . '/')) {
  23. return null;
  24. } else {
  25. $path = substr($path, strlen($root));
  26. return self::normalizePath($path);
  27. }
  28. }
  29. /**
  30. * @param string $path
  31. * @return string
  32. */
  33. public static function normalizePath(string $path): string {
  34. if ($path === '' or $path === '/') {
  35. return '/';
  36. }
  37. //no windows style slashes
  38. $path = str_replace('\\', '/', $path);
  39. //add leading slash
  40. if ($path[0] !== '/') {
  41. $path = '/' . $path;
  42. }
  43. //remove duplicate slashes
  44. while (str_contains($path, '//')) {
  45. $path = str_replace('//', '/', $path);
  46. }
  47. //remove trailing slash
  48. $path = rtrim($path, '/');
  49. return $path;
  50. }
  51. }