From 5573fbb772a887bddd0717f68616048b67f89a24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vojt=C4=9Bch=20Dobe=C5=A1?= Date: Mon, 14 Jul 2014 13:26:26 +0200 Subject: [PATCH] PhpAdapter supports prevention of array merging --- src/DI/Config/Adapters/PhpAdapter.php | 34 +++++++++++++++++++++++++-- tests/DI/Loader.include.phpt | 13 ++++++++++ tests/DI/files/loader.includes.php | 14 +++++++++++ 3 files changed, 59 insertions(+), 2 deletions(-) create mode 100644 tests/DI/files/loader.includes.php diff --git a/src/DI/Config/Adapters/PhpAdapter.php b/src/DI/Config/Adapters/PhpAdapter.php index bfe158a58..c426d1ae5 100644 --- a/src/DI/Config/Adapters/PhpAdapter.php +++ b/src/DI/Config/Adapters/PhpAdapter.php @@ -7,7 +7,8 @@ namespace Nette\DI\Config\Adapters; -use Nette; +use Nette, + Nette\DI\Config\Helpers; /** @@ -17,6 +18,8 @@ */ class PhpAdapter extends Nette\Object implements Nette\DI\Config\IAdapter { + /** @internal */ + const PREVENT_MERGING = '!'; /** * Reads configuration from PHP file. @@ -25,7 +28,34 @@ class PhpAdapter extends Nette\Object implements Nette\DI\Config\IAdapter */ public function load($file) { - return require $file; + $config = require $file; + if (is_array($config)) { + return $this->process($config); + } + return $config; + } + + + private function process(array $arr) + { + $res = array(); + foreach ($arr as $key => $val) { + if (substr($key, -1) === self::PREVENT_MERGING) { + if (!is_array($val) && $val !== NULL) { + throw new Nette\InvalidStateException("Replacing operator is available only for arrays, item '$key' is not array."); + } + $key = substr($key, 0, -1); + $val[Helpers::EXTENDS_KEY] = Helpers::OVERWRITE; + + } + + if (is_array($val)) { + $val = $this->process($val); + + } + $res[$key] = $val; + } + return $res; } diff --git a/tests/DI/Loader.include.phpt b/tests/DI/Loader.include.phpt index 0f236d677..08e363ebe 100644 --- a/tests/DI/Loader.include.phpt +++ b/tests/DI/Loader.include.phpt @@ -31,3 +31,16 @@ Assert::same( array( 'force' => array(1, 2), ), ), $data ); + +$data = $config->load('files/loader.includes.php', 'common'); + +Assert::same( array( + 'parameters' => array( + 'me' => array( + 'loader.includes.child.php', + ), + 'scalar' => 1, + 'list' => array(5, 6, 1, 2), + 'force' => array(1, 2), + ), +), $data ); diff --git a/tests/DI/files/loader.includes.php b/tests/DI/files/loader.includes.php new file mode 100644 index 000000000..c46220667 --- /dev/null +++ b/tests/DI/files/loader.includes.php @@ -0,0 +1,14 @@ + array( + 'includes' => array( + 'loader.includes.child.php', + ), + 'parameters' => array( + 'scalar' => 1, + 'list' => array(1, 2), + 'force!' => array(1, 2), + ), + ), +);