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

array_filter compatibility #7315

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
49 changes: 49 additions & 0 deletions library/Zend/Stdlib/ArrayUtils.php
Expand Up @@ -20,6 +20,16 @@
*/
abstract class ArrayUtils
{
/**
* Compatibility Flag for ArrayUtils::filter
*/
const ARRAY_FILTER_USE_BOTH = 1;

/**
* Compatibility Flag for ArrayUtils::filter
*/
const ARRAY_FILTER_USE_KEY = 2;

/**
* Test whether an array contains one or more string keys
*
Expand Down Expand Up @@ -280,4 +290,43 @@ public static function merge(array $a, array $b, $preserveNumericKeys = false)

return $a;
}

/**
* Compatibility Method for array_filter on <5.6 systems
*
* @param array $data
* @param callable $callback
* @param null|int $flag
* @return array
*/
public static function filter(array $data, $callback, $flag = null)
{
if (!is_callable($callback)) {
throw new Exception\InvalidArgumentException('Second parameter of ' . __METHOD__ . 'must be callable');
}

if (version_compare(PHP_VERSION, '5.6.0') >= 0) {
return array_filter($data, $callback, $flag);
}

$output = array();
foreach ($data as $key => $value) {
$params = array($value);

if ($flag === static::ARRAY_FILTER_USE_BOTH) {
$params[] = $key;
}

if ($flag === static::ARRAY_FILTER_USE_KEY) {
$params = array($key);
}

$response = call_user_func_array($callback, $params);
if ($response) {
$output[$key] = $value;
}
}

return $output;
}
}
60 changes: 60 additions & 0 deletions tests/ZendTest/Stdlib/ArrayUtilsTest.php
Expand Up @@ -482,4 +482,64 @@ public function testInvalidIteratorsRaiseInvalidArgumentException($test)
$this->setExpectedException('Zend\Stdlib\Exception\InvalidArgumentException');
$this->assertFalse(ArrayUtils::iteratorToArray($test));
}

public function filterArrays()
{
return array(
array(
array('foo' => 'bar', 'fiz' => 'buz'),
function($value) {
if ($value == 'bar') {
return false;
}
return true;
},
null,
array('fiz' => 'buz')
),
array(
array('foo' => 'bar', 'fiz' => 'buz'),
function($value, $key) {
if ($value == 'buz') {
return false;
}

if ($key == 'foo') {
return false;
}

return true;
},
ArrayUtils::ARRAY_FILTER_USE_BOTH,
array()
),
array(
array('foo' => 'bar', 'fiz' => 'buz'),
function($key) {
if ($key == 'foo') {
return false;
}
return true;
},
ArrayUtils::ARRAY_FILTER_USE_KEY,
array('fiz' => 'buz')
),
);
}

/**
* @dataProvider filterArrays
*/
public function testFiltersArray($data, $callback, $flag, $result)
{
$this->assertEquals($result, ArrayUtils::filter($data, $callback, $flag));
}

/**
* @expectedException \Zend\Stdlib\Exception\InvalidArgumentException
*/
public function testInvalidCallableRaiseInvalidArgumentException()
{
ArrayUtils::filter(array(), "INVALID");
}
}