RelativePathConverter.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. /**
  7. * Helper that can convert relative paths from system.xml to absolute
  8. */
  9. namespace Magento\Config\Model\Config\Structure\Mapper\Helper;
  10. /**
  11. * @api
  12. * @since 100.0.2
  13. */
  14. class RelativePathConverter
  15. {
  16. /**
  17. * Convert relative path from system.xml to absolute
  18. *
  19. * @param string $nodePath
  20. * @param string $relativePath
  21. * @return string
  22. * @throws \InvalidArgumentException
  23. */
  24. public function convert($nodePath, $relativePath)
  25. {
  26. $nodePath = trim($nodePath);
  27. $relativePath = trim($relativePath);
  28. if (empty($nodePath) || empty($relativePath)) {
  29. throw new \InvalidArgumentException('Invalid arguments');
  30. }
  31. $relativePathParts = explode('/', $relativePath);
  32. $pathParts = explode('/', $nodePath);
  33. $relativePartsCount = count($relativePathParts);
  34. $pathPartsCount = count($pathParts);
  35. if ($relativePartsCount === 1 && $pathPartsCount > 1) {
  36. $relativePathParts = array_pad($relativePathParts, -$pathPartsCount, '*');
  37. }
  38. $realPath = [];
  39. foreach ($relativePathParts as $index => $path) {
  40. if ($path === '*') {
  41. if (false == array_key_exists($index, $pathParts)) {
  42. throw new \InvalidArgumentException(
  43. sprintf('Invalid relative path %s in %s node', $relativePath, $nodePath)
  44. );
  45. }
  46. $path = $pathParts[$index];
  47. }
  48. $realPath[$index] = $path;
  49. }
  50. return implode('/', $realPath);
  51. }
  52. }