zendframework / zend-config

Config component from Zend Framework
BSD 3-Clause "New" or "Revised" License
90 stars 38 forks source link

What do you think about adding env processor for static files ? #50

Open eguvenc opened 6 years ago

eguvenc commented 6 years ago

Code to reproduce the issue

# amqp.yaml
# 
amqp:
    host: 127.0.0.1
    port: 5672
    username: 'env(AMQP_USERNAME)'
    password: 'env(AMQP_PASSWORD)'
    vhost: /

namespace Zend\Config\Processor;

use Zend\Config\Config;
use Zend\Config\Exception;
use Zend\Config\Processor\Token;
use Zend\Config\Processor\ProcessorInterface;

class Env extends Token implements ProcessorInterface
{
    protected function doProcess($value, array $replacements)
    {
        if (! is_string($value)) {
            return parent::doProcess($value, $replacements);
        }

        if (false === strpos($value, 'env(')) {
            return parent::doProcess($value, $replacements);
        }

        $value = $this->parseEnvRecursive($value);

        return $value;
    }

    /**
     * Parse env variables
     * 
     * @param mixed $input input
     * @return string
     */
    protected function parseEnvRecursive($input)
    {
        $regex = '/env\((.*?)\)/';
        if (is_array($input)) {
            $input = getenv($input[1]);
        }
        return preg_replace_callback($regex, array($this, 'parseEnvRecursive'), $input);
    }
}

require 'vendor/autoload.php';

use Symfony\Component\Yaml\Yaml as SymfonyYaml;
use Zend\Config\Config;
use Zend\Config\Factory;
use Zend\Config\Processor;
use Zend\Config\Reader\Yaml as YamlConfig;

Factory::registerReader('yaml', new YamlConfig([SymfonyYaml::class, 'parse']));

putenv('AMQP_USERNAME=guest');

$config = Factory::fromFile(dirname(__FILE__).'/config/amqp.yaml');

$config = new Config($config, true);
$processor = new Processor\Env();
$processor->process($config);
$config->setReadOnly();

echo $config->amqp->username; // guest

Expected results

// guest

weierophinney commented 4 years ago

This repository has been closed and moved to laminas/laminas-config; a new issue has been opened at https://github.com/laminas/laminas-config/issues/3.