EnvironmentConfigSource.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Config\App\Config\Source;
  7. use Magento\Framework\App\Config\ConfigSourceInterface;
  8. use Magento\Framework\DataObject;
  9. use Magento\Config\Model\Placeholder\PlaceholderFactory;
  10. use Magento\Config\Model\Placeholder\PlaceholderInterface;
  11. use Magento\Framework\Stdlib\ArrayManager;
  12. /**
  13. * Class for retrieving configurations from environment variables.
  14. *
  15. * @api
  16. * @since 101.0.0
  17. */
  18. class EnvironmentConfigSource implements ConfigSourceInterface
  19. {
  20. /**
  21. * Library for working with arrays.
  22. *
  23. * @var ArrayManager
  24. */
  25. private $arrayManager;
  26. /**
  27. * Object for working with placeholders for environment variables.
  28. *
  29. * @var PlaceholderInterface
  30. */
  31. private $placeholder;
  32. /**
  33. * @param ArrayManager $arrayManager
  34. * @param PlaceholderFactory $placeholderFactory
  35. */
  36. public function __construct(
  37. ArrayManager $arrayManager,
  38. PlaceholderFactory $placeholderFactory
  39. ) {
  40. $this->arrayManager = $arrayManager;
  41. $this->placeholder = $placeholderFactory->create(PlaceholderFactory::TYPE_ENVIRONMENT);
  42. }
  43. /**
  44. * @inheritdoc
  45. * @since 101.0.0
  46. */
  47. public function get($path = '')
  48. {
  49. $data = new DataObject($this->loadConfig());
  50. return $data->getData($path) ?: [];
  51. }
  52. /**
  53. * Loads config from environment variables.
  54. *
  55. * @return array
  56. */
  57. private function loadConfig()
  58. {
  59. $config = [];
  60. $environmentVariables = $_ENV;
  61. foreach ($environmentVariables as $template => $value) {
  62. if (!$this->placeholder->isApplicable($template)) {
  63. continue;
  64. }
  65. $config = $this->arrayManager->set(
  66. $this->placeholder->restore($template),
  67. $config,
  68. $value
  69. );
  70. }
  71. return $config;
  72. }
  73. }