Add `filterTo()` and `filterNotTo()`

This commit is contained in:
CismonX 2018-04-14 14:03:47 +08:00
parent 9b08894ae5
commit d2506ee5c9
2 changed files with 48 additions and 5 deletions

View File

@ -308,9 +308,9 @@ PHP_METHOD(Collection, associateBy)
PHP_METHOD(Collection, associateByTo)
{
zval* dest;
zend_fcall_info fci;
zend_fcall_info_cache fcc;
zval* dest;
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_OBJECT_OF_CLASS(dest, collections_collection_ce)
Z_PARAM_FUNC(fci, fcc)
@ -635,12 +635,48 @@ PHP_METHOD(Collection, filterNot)
PHP_METHOD(Collection, filterNotTo)
{
zval* dest;
zend_fcall_info fci;
zend_fcall_info_cache fcc;
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_OBJECT_OF_CLASS(dest, collections_collection_ce)
Z_PARAM_FUNC(fci, fcc)
ZEND_PARSE_PARAMETERS_END();
INIT_FCI();
zval* current = COLLECTION_FETCH_EX();
zend_array* dest_arr = Z_ARRVAL_P(COLLECTION_FETCH(dest));
ZEND_HASH_FOREACH_BUCKET(Z_ARRVAL_P(current), Bucket* bucket)
CALLBACK_KEYVAL_INVOKE(params, bucket);
if (!zend_is_true(&retval))
if (bucket->key)
zend_hash_add(dest_arr, bucket->key, &bucket->val);
else
zend_hash_next_index_insert(dest_arr, &bucket->val);
ZEND_HASH_FOREACH_END();
RETVAL_ZVAL(dest, 1, 0);
}
PHP_METHOD(Collection, filterTo)
{
zval* dest;
zend_fcall_info fci;
zend_fcall_info_cache fcc;
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_OBJECT_OF_CLASS(dest, collections_collection_ce)
Z_PARAM_FUNC(fci, fcc)
ZEND_PARSE_PARAMETERS_END();
INIT_FCI();
zval* current = COLLECTION_FETCH_EX();
zend_array* dest_arr = Z_ARRVAL_P(COLLECTION_FETCH(dest));
ZEND_HASH_FOREACH_BUCKET(Z_ARRVAL_P(current), Bucket* bucket)
CALLBACK_KEYVAL_INVOKE(params, bucket);
if (zend_is_true(&retval))
if (bucket->key)
zend_hash_add(dest_arr, bucket->key, &bucket->val);
else
zend_hash_next_index_insert(dest_arr, &bucket->val);
ZEND_HASH_FOREACH_END();
RETVAL_ZVAL(dest, 1, 0);
}
PHP_METHOD(Collection, find)

View File

@ -1,5 +1,5 @@
--TEST--
Test Collection::filter() and Collection::filterNot().
Test Collection::filter(), Collection::filterNot(), Collection::filterTo(), Collection::filterNotTo().
--FILE--
<?php
$array = [1, 3, 4, 5, 8, 10, 13];
@ -14,6 +14,13 @@ $collection1 = Collection::init($array)->filterNot($pred_is_odd);
if ($collection->toArray() != array_filter($array, $pred_is_odd))
echo 'Collection::filter() failed.', PHP_EOL;
if ($collection1->toArray() != array_filter($array, $pred_is_even))
echo 'Collection::filter() failed.', PHP_EOL;
echo 'Collection::filterNot() failed.', PHP_EOL;
$dest = Collection::init($array);
$collection2 = Collection::init($array)->filterTo($dest, $pred_is_odd);
if ($collection2->toArray() != array_merge($array, $collection->toArray()))
echo 'Collection::filterTo() failed.', PHP_EOL;
$collection3 = Collection::init($array)->filterNotTo($dest, $pred_is_odd);
if ($collection3->toArray() != array_merge($array, $collection->toArray(), $collection1->toArray()))
echo 'Collection::filterNotTo() failed.', PHP_EOL;
?>
--EXPECT--