PathValidator.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. declare(strict_types=1);
  7. namespace Magento\Framework\Filesystem\Directory;
  8. use Magento\Framework\Exception\ValidatorException;
  9. use Magento\Framework\Filesystem\DriverInterface;
  10. use Magento\Framework\Phrase;
  11. /**
  12. * @inheritDoc
  13. *
  14. * Validates paths using driver.
  15. */
  16. class PathValidator implements PathValidatorInterface
  17. {
  18. /**
  19. * @var DriverInterface
  20. */
  21. private $driver;
  22. /**
  23. * @param DriverInterface $driver
  24. */
  25. public function __construct(DriverInterface $driver)
  26. {
  27. $this->driver = $driver;
  28. }
  29. /**
  30. * @inheritDoc
  31. */
  32. public function validate(
  33. string $directoryPath,
  34. string $path,
  35. ?string $scheme = null,
  36. bool $absolutePath = false
  37. ): void {
  38. $realDirectoryPath = $this->driver->getRealPathSafety($directoryPath);
  39. if ($realDirectoryPath[-1] !== DIRECTORY_SEPARATOR) {
  40. $realDirectoryPath .= DIRECTORY_SEPARATOR;
  41. }
  42. if (!$absolutePath) {
  43. $actualPath = $this->driver->getRealPathSafety(
  44. $this->driver->getAbsolutePath(
  45. $realDirectoryPath,
  46. $path,
  47. $scheme
  48. )
  49. );
  50. } else {
  51. $actualPath = $this->driver->getRealPathSafety($path);
  52. }
  53. if (mb_strpos($actualPath, $realDirectoryPath) !== 0
  54. && $path .DIRECTORY_SEPARATOR !== $realDirectoryPath
  55. ) {
  56. throw new ValidatorException(
  57. new Phrase(
  58. 'Path "%1" cannot be used with directory "%2"',
  59. [$path, $directoryPath]
  60. )
  61. );
  62. }
  63. }
  64. }