ComplexParameter.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\Shell;
  7. /**
  8. * A parser for complex parameters in command-line arguments
  9. *
  10. * Transforms parameter formatted as a URL query string into an array
  11. */
  12. class ComplexParameter
  13. {
  14. /**
  15. * Default regex pattern for searching the parameter
  16. */
  17. const DEFAULT_PATTERN = '/^\-\-%s=(.+)$/';
  18. /**
  19. * Argument name
  20. *
  21. * @var string
  22. */
  23. private $name;
  24. /**
  25. * Regex pattern for searching the parameter among arguments
  26. *
  27. * @var string
  28. */
  29. private $pcre;
  30. /**
  31. * Constructor
  32. *
  33. * @param string $name
  34. * @param string $pattern
  35. */
  36. public function __construct($name, $pattern = self::DEFAULT_PATTERN)
  37. {
  38. $this->name = $name;
  39. $this->pcre = sprintf($pattern, preg_quote($name, '/'));
  40. }
  41. /**
  42. * Searches and parses the value from an array of arguments
  43. *
  44. * @param string[] $input
  45. * @return array
  46. */
  47. public function getFromArray($input)
  48. {
  49. foreach ($input as $row) {
  50. $result = $this->getFromString($row);
  51. if ($result) {
  52. return $result;
  53. }
  54. }
  55. return [];
  56. }
  57. /**
  58. * Parses the value from a specified argument string
  59. *
  60. * @param string $string
  61. * @return array
  62. */
  63. public function getFromString($string)
  64. {
  65. if (preg_match($this->pcre, $string, $matches)) {
  66. parse_str($matches[1], $result);
  67. return $result;
  68. }
  69. return [];
  70. }
  71. /**
  72. * Searches the value parameter in an "argv" array and merges it recursively into specified array
  73. *
  74. * @param array $server
  75. * @param array $into
  76. * @return array
  77. */
  78. public function mergeFromArgv($server, array $into = [])
  79. {
  80. $result = $into;
  81. if (isset($server['argv'])) {
  82. $value = $this->getFromArray($server['argv']);
  83. $result = array_replace_recursive($into, $value);
  84. }
  85. return $result;
  86. }
  87. }