Skip to content

Instantly share code, notes, and snippets.

@davidyell
Created August 16, 2017 14:50
Show Gist options
  • Save davidyell/03bfab218a9977eb95b12bdb34f73056 to your computer and use it in GitHub Desktop.
Save davidyell/03bfab218a9977eb95b12bdb34f73056 to your computer and use it in GitHub Desktop.
<?php
namespace Neon1024\ArrayReduce;
class ArrayReduce
{
/**
* Reduce an input array by removing fields which are present in the second array argument
*
* @param array $target The array of data to reduce
* @param array $reduceBy Array of array keys to be removed from the target array
* @return array
*/
public function reduce(array $target, array $reduceBy)
{
$filtered = array_filter($target, function ($value, $key) use ($reduceBy) {
if (!in_array($key, $reduceBy)) {
return false;
}
return true;
}, ARRAY_FILTER_USE_BOTH);
return $filtered;
}
}
<?php
namespace Neon1024\Tests;
use PHPUnit\Framework\TestCase;
use Neon1024\ArrayReduce\ArrayReduce;
class ArrayReduceTest extends TestCase
{
public function setUp()
{
require 'vendor/autoload.php';
}
public function testReduce()
{
$fieldToUpdate = [
'id',
'name',
'modified'
];
$responseData = [
'id' => 9,
'name' => 'Example',
'description' => 'The description',
'something' => 'else',
'created' => (new \DateTime())->format('Y-m-d\TH:i:sP'),
'modified' => (new \DateTime())->format('Y-m-d\TH:i:sP')
];
$reducer = new ArrayReduce();
$result = $reducer->reduce($responseData, $fieldToUpdate);
$expected = [
'id' => 9,
'name' => 'Example',
'modified' => (new \DateTime())->format('Y-m-d\TH:i:sP')
];
$this->assertEquals($expected, $result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment