zendframework / zend-expressive-template

Template subcomponent for Expressive
BSD 3-Clause "New" or "Revised" License
20 stars 5 forks source link

addDefaultParam in DefaultParamsTrait duplicates arrays #7

Closed Musiksammler closed 7 years ago

Musiksammler commented 8 years ago

Hello!

I've the following line in my code:

$locales = ['en_GB', 'de_DE'];
$this->templateRenderer->addDefaultParam(
    TemplateRendererInterface::TEMPLATE_ALL,
    'availableLocales',
    $locales
);

When I loop through the array in my template

{% for locale in availableLocales %}
    <a href="/{{ locale }}{{ path() }}">{{ locale }}</a>
{% endfor %}

every value is printed twice!

The reason might be this in DefaultsParamsTrait:

private function merge(array $a, array $b)
{
            ...

            if (is_array($value) && is_array($a[$key])) {
                $a[$key] = $this->merge($a[$key], $value);
                continue;
            }

            ...
}

After all global and template defaults and the normal template variables are parsed "availableLocales" has the content:

[0 => 'en_GB, 1 => 'de_DE', 2 => 'en_GB, 3 => 'de_DE']

When I replace that "$this->merge(...)" with "array_replace_recursive($a[$key], $value)" I get the result I originally expected:

if (is_array($value) && is_array($a[$key])) {
    $a[$key] = array_replace_recursive($a[$key], $value);
    continue;
}

[0 => 'en_GB, 1 => 'de_DE']

Since I don't know if there is another reason for that "$this->merge" I didn't create a pull request. It would be nice if that can be fixed as soon as possible.

P.S.: a global "return array_replace_recursive($a, $b);" as the only line for the "merge" function works for me without any problems. But that replaces previously existing keys and doesn't append them as the merge-function does it now.