Add ValueError for invalid mode in count()

Closes GH-5106
This commit is contained in:
George Peter Banyard 2020-01-22 01:55:12 +01:00
parent 4281c2a989
commit 0719035f9d
3 changed files with 50 additions and 20 deletions

View File

@ -764,6 +764,11 @@ PHP_FUNCTION(count)
Z_PARAM_LONG(mode) Z_PARAM_LONG(mode)
ZEND_PARSE_PARAMETERS_END(); ZEND_PARSE_PARAMETERS_END();
if (mode != COUNT_NORMAL && mode != COUNT_RECURSIVE) {
zend_value_error("Mode value is invalid");
RETURN_THROWS();
}
switch (Z_TYPE_P(array)) { switch (Z_TYPE_P(array)) {
case IS_NULL: case IS_NULL:
/* Intentionally not converted to an exception */ /* Intentionally not converted to an exception */

View File

@ -0,0 +1,37 @@
--TEST--
Test count() function : invalid modes in weak type mode
--FILE--
<?php
$modes = [
COUNT_NORMAL,
COUNT_RECURSIVE,
0,
1,
-1,
-1.45,
2,
TRUE,
FALSE,
NULL,
];
foreach ($modes as $mode) {
try {
var_dump(count([], $mode));
} catch (\ValueError $error) {
echo $error->getMessage() . \PHP_EOL;
}
}
?>
--EXPECT--
int(0)
int(0)
int(0)
int(0)
Mode value is invalid
Mode value is invalid
Mode value is invalid
int(0)
int(0)
int(0)

View File

@ -104,14 +104,10 @@ echo "\n-- Testing count() on arrays containing references --\n";
$arr = array(1, array("a", "b", "c")); $arr = array(1, array("a", "b", "c"));
$arr[2] = &$arr[1]; $arr[2] = &$arr[1];
$mode_arr = array( COUNT_NORMAL, COUNT_RECURSIVE, 0, 1, -1, -1.45, 2, TRUE, echo "Count normal" . \PHP_EOL;
FALSE, NULL); var_dump(count($arr, COUNT_NORMAL));
for( $i =0; $i < count( $mode_arr ); $i++) { echo "Count recursive" . \PHP_EOL;
echo "For mode '$mode_arr[$i]' count is => "; var_dump(count($arr, COUNT_RECURSIVE));
var_dump(count($arr, $mode_arr[$i]));
}
echo "\nDone";
/* closing the resource handles */ /* closing the resource handles */
fclose( $resource1 ); fclose( $resource1 );
@ -209,15 +205,7 @@ COUNT_NORMAL: should be 3, is 3
int(2) int(2)
-- Testing count() on arrays containing references -- -- Testing count() on arrays containing references --
For mode '0' count is => int(3) Count normal
For mode '1' count is => int(9) int(3)
For mode '0' count is => int(3) Count recursive
For mode '1' count is => int(9) int(9)
For mode '-1' count is => int(3)
For mode '-1.45' count is => int(3)
For mode '2' count is => int(3)
For mode '1' count is => int(9)
For mode '' count is => int(3)
For mode '' count is => int(3)
Done