WhitespacePathNormalizer.php 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. declare(strict_types=1);
  3. namespace League\Flysystem;
  4. class WhitespacePathNormalizer implements PathNormalizer
  5. {
  6. public function normalizePath(string $path): string
  7. {
  8. $path = str_replace('\\', '/', $path);
  9. $this->rejectFunkyWhiteSpace($path);
  10. return $this->normalizeRelativePath($path);
  11. }
  12. private function rejectFunkyWhiteSpace(string $path): void
  13. {
  14. if (preg_match('#\p{C}+#u', $path)) {
  15. throw CorruptedPathDetected::forPath($path);
  16. }
  17. }
  18. private function normalizeRelativePath(string $path): string
  19. {
  20. $parts = [];
  21. foreach (explode('/', $path) as $part) {
  22. switch ($part) {
  23. case '':
  24. case '.':
  25. break;
  26. case '..':
  27. if (empty($parts)) {
  28. throw PathTraversalDetected::forPath($path);
  29. }
  30. array_pop($parts);
  31. break;
  32. default:
  33. $parts[] = $part;
  34. break;
  35. }
  36. }
  37. return implode('/', $parts);
  38. }
  39. }