Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PhpAdapter supports prevention of array merging #7

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 32 additions & 2 deletions src/DI/Config/Adapters/PhpAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@

namespace Nette\DI\Config\Adapters;

use Nette;
use Nette,
Nette\DI\Config\Helpers;


/**
Expand All @@ -17,6 +18,8 @@
*/
class PhpAdapter extends Nette\Object implements Nette\DI\Config\IAdapter
{
/** @internal */
const PREVENT_MERGING = '!';

/**
* Reads configuration from PHP file.
Expand All @@ -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;
}


Expand Down
13 changes: 13 additions & 0 deletions tests/DI/Loader.include.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -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 );
14 changes: 14 additions & 0 deletions tests/DI/files/loader.includes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

return array(
'common' => array(
'includes' => array(
'loader.includes.child.php',
),
'parameters' => array(
'scalar' => 1,
'list' => array(1, 2),
'force!' => array(1, 2),
),
),
);