Skip to content

Commit

Permalink
Merge pull request #4 from texnikru/ftr_patch
Browse files Browse the repository at this point in the history
Patch for arrays by @texnikru
  • Loading branch information
maciejczyzewski committed Aug 5, 2014
2 parents 9b1a058 + 69bc207 commit df90c95
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 0 deletions.
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,15 @@ Bottomline is based on namespaces and dynamic autoloader. The main file is `load
// → [1, 2, 3, 4]
```

- [__::patch](src/__/arrays/patch.php)

Patches array with list of xpath-value pairs.

```php
__::patch(['addr' => ['country' => 'US', 'zip' => 12345]], ['/addr/country' => 'CA', '/addr/zip' => 54321]);
// → ['addr' => ['country' => 'CA', 'zip' => 54321]]
```

- [__::prepend](src/__/arrays/prepend.php)

```php
Expand Down
45 changes: 45 additions & 0 deletions src/__/arrays/patch.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

namespace arrays;

/**
* Patches array by xpath.
*
* Arguments:
* (Array): The array to patch.
* (Array): List of new xpath-value pairs.
*
* Returns:
* (Array): Returns patched array.
*
* @arrays @patch
*
** __::patch(['addr' => ['country' => 'US', 'zip' => 12345]], ['/addr/country' => 'CA', '/addr/zip' => 54321]);
** // → ['addr' => ['country' => 'CA', 'zip' => 54321]]
*/

function patch($arr, $patches, $parent = '')
{
foreach($arr as $key => $value)
{
$z = $parent . '/' . $key;

if( isset($patches[$z]) )
{
$arr[ $key ] = $patches[$z];
unset( $patches[$z] );

if( !count($patches) )
{
break;
}
}

if( is_array($value) )
{
$arr[ $key ] = patch($value, $patches, $z);
}
}

return $arr;
}
13 changes: 13 additions & 0 deletions tests/arrays.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,19 @@ public function testFlatten()
$this->assertEquals([1, 2, 3, 4], $x);
}

public function testPatch()
{
// Arrange
$a = [1, 1, 1, 'contacts' => ['country' => 'US', 'tel' => [123]], 99];
$p = ['/0' => 2, '/1' => 3, '/contacts/country' => 'CA', '/contacts/tel/0' => 3456];

// Act
$x = __::patch($a, $p);

// Assert
$this->assertEquals([2, 3, 1, 'contacts' => ['country' => 'CA', 'tel' => [3456]], 99], $x);
}

public function testPrepend()
{
// Arrange
Expand Down

0 comments on commit df90c95

Please sign in to comment.