Support environment variables as input data; add JSON escape strategy

Merge pull request #1 from peets/master
This commit is contained in:
dana 2018-02-18 16:45:47 -06:00 committed by GitHub
commit f294101183
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 25 additions and 1 deletions

View file

@ -10,7 +10,7 @@ vendor:
composer install
twigc.phar: vendor
php bin/compile
php -d phar.readonly=0 bin/compile
build: twigc.phar

View file

@ -19,6 +19,7 @@ Options:
-V, --version Display version information
--credits Display dependency credits (including Twig version)
-d, --dir=DIR Add search directory to loader (multiple values allowed)
--env Treat environment variables as input data
-e, --escape=ESCAPE Set autoescape environment option
-j, --json=JSON Pass variables as JSON (dictionary string or file path)
-p, --pair=PAIR Pass variable as key=value pair (multiple values allowed)

View file

@ -63,6 +63,12 @@ class DefaultCommand extends Command {
InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
'Add search directory to loader'
)
->addOption(
'env',
null,
InputOption::VALUE_NONE,
'Treat environment variables as input data'
)
->addOption(
'escape',
'e',
@ -254,6 +260,9 @@ class DefaultCommand extends Command {
case 'js':
$escape = 'js';
break;
case 'json':
$escape = 'json';
break;
default:
$escape = false;
break;
@ -349,6 +358,10 @@ class DefaultCommand extends Command {
}
}
if ( $input->getOption('env') ) {
$inputData = array_merge($_ENV, $inputData);
}
// Validate key names now
foreach ( $inputData as $key => $value ) {
if ( ! preg_match('#^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$#', $key) ) {
@ -399,6 +412,16 @@ class DefaultCommand extends Command {
'autoescape' => $escape,
]);
$twig->getExtension('core')->setEscaper(
'json',
function($twigEnv, $string, $charset) {
return json_encode(
$string,
\JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE
);
}
);
$output->writeln(
rtrim($twig->render(basename($template), $inputData), "\r\n")
);