Skip to content
This repository has been archived by the owner on Jan 31, 2020. It is now read-only.

Commit

Permalink
Merge branch 'feature/zendframework/zendframework#6899-arrayutils-mer…
Browse files Browse the repository at this point in the history
…ge-ability-to-remove-keys' into develop

Close zendframework/zendframework#6899
  • Loading branch information
Ocramius committed Dec 6, 2014
2 parents 1cf8662 + 157add3 commit 1756cda
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 4 deletions.
9 changes: 7 additions & 2 deletions src/ArrayUtils.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
namespace Zend\Stdlib;

use Traversable;
use Zend\Stdlib\ArrayUtils\MergeRemoveKey;

/**
* Utility class for testing and manipulation of PHP arrays.
Expand Down Expand Up @@ -258,15 +259,19 @@ public static function merge(array $a, array $b, $preserveNumericKeys = false)
{
foreach ($b as $key => $value) {
if (isset($a[$key]) || array_key_exists($key, $a)) {
if (!$preserveNumericKeys && is_int($key)) {
if ($value instanceof MergeRemoveKey) {
unset($a[$key]);
} elseif (!$preserveNumericKeys && is_int($key)) {
$a[] = $value;
} elseif (is_array($value) && is_array($a[$key])) {
$a[$key] = static::merge($a[$key], $value, $preserveNumericKeys);
} else {
$a[$key] = $value;
}
} else {
$a[$key] = $value;
if (!$value instanceof MergeRemoveKey) {
$a[$key] = $value;
}
}
}

Expand Down
14 changes: 14 additions & 0 deletions src/ArrayUtils/MergeRemoveKey.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/

namespace Zend\Stdlib\ArrayUtils;

final class MergeRemoveKey
{
}
24 changes: 22 additions & 2 deletions test/ArrayUtilsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@

namespace ZendTest\Stdlib;

use ArrayObject;
use PHPUnit_Framework_TestCase as TestCase;
use stdClass;
use ArrayObject;
use Zend\Stdlib\ArrayUtils;
use Zend\Config\Config;
use Zend\Stdlib\ArrayUtils;
use Zend\Stdlib\ArrayUtils\MergeRemoveKey;

class ArrayUtilsTest extends TestCase
{
Expand Down Expand Up @@ -263,6 +264,25 @@ public static function mergeArrays()
);
}

/**
* @group 6899
*/
public function testAllowsRemovingKeys()
{
$a = array(
'foo' => 'bar',
'bar' => 'bat'
);
$b = array(
'foo' => new MergeRemoveKey(),
'baz' => new MergeRemoveKey(),
);
$expected = array(
'bar' => 'bat'
);
$this->assertEquals($expected, ArrayUtils::merge($a, $b));
}

public static function validIterators()
{
return array(
Expand Down

0 comments on commit 1756cda

Please sign in to comment.