Skip to content

Commit 1ea389d

Browse files
committed
Make iterator_count() accept all iterables
1 parent 3ae365d commit 1ea389d

File tree

5 files changed

+27
-9
lines changed

5 files changed

+27
-9
lines changed

ext/spl/php_spl.stub.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ function spl_object_id(object $object): int {}
4848

4949
function iterator_apply(Traversable $iterator, callable $callback, ?array $args = null): int {}
5050

51-
function iterator_count(Traversable $iterator): int {}
51+
function iterator_count(iterable $iterator): int {}
5252

5353
/** @refcount 1 */
5454
function iterator_to_array(iterable $iterator, bool $preserve_keys = true): array {}

ext/spl/php_spl_arginfo.h

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

ext/spl/spl_iterators.c

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3205,12 +3205,16 @@ PHP_FUNCTION(iterator_count)
32053205
zval *obj;
32063206
zend_long count = 0;
32073207

3208-
if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &obj, zend_ce_traversable) == FAILURE) {
3209-
RETURN_THROWS();
3210-
}
3208+
ZEND_PARSE_PARAMETERS_START(1, 1)
3209+
Z_PARAM_ITERABLE(obj)
3210+
ZEND_PARSE_PARAMETERS_END();
32113211

3212-
if (spl_iterator_apply(obj, spl_iterator_count_apply, (void*)&count) == FAILURE) {
3213-
return;
3212+
if (Z_TYPE_P(obj) == IS_ARRAY) {
3213+
count = zend_hash_num_elements(Z_ARRVAL_P(obj));
3214+
} else {
3215+
if (spl_iterator_apply(obj, spl_iterator_count_apply, (void*)&count) == FAILURE) {
3216+
return;
3217+
}
32143218
}
32153219

32163220
RETURN_LONG(count);

ext/spl/tests/iterator_count.phpt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ iterator_count('1');
1313

1414
?>
1515
--EXPECTF--
16-
Fatal error: Uncaught TypeError: iterator_count(): Argument #1 ($iterator) must be of type Traversable, string given in %s:%d
16+
Fatal error: Uncaught TypeError: iterator_count(): Argument #1 ($iterator) must be of type Traversable|array, string given in %s:%d
1717
Stack trace:
1818
#0 %s(%d): iterator_count('1')
1919
#1 {main}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
--TEST--
2+
SPL: iterator_count() supports arrays.
3+
--FILE--
4+
<?php
5+
6+
var_dump(iterator_count([]));
7+
var_dump(iterator_count([1]));
8+
var_dump(iterator_count(['a' => 1, 'b' => 2, 5 => 3]));
9+
10+
?>
11+
--EXPECTF--
12+
int(0)
13+
int(1)
14+
int(3)

0 commit comments

Comments
 (0)