]> granicus.if.org Git - php/commitdiff
Add ValueError for invalid mode in count()
authorGeorge Peter Banyard <girgias@php.net>
Wed, 22 Jan 2020 00:55:12 +0000 (01:55 +0100)
committerGeorge Peter Banyard <girgias@php.net>
Wed, 22 Jan 2020 23:14:20 +0000 (00:14 +0100)
Closes GH-5106

ext/standard/array.c
ext/standard/tests/array/count_invalid_mode.phpt [new file with mode: 0644]
ext/standard/tests/array/count_recursive.phpt

index 3624881c4c7ae9c298506776ba4c4a717cdb67a3..9e0af6f07c00648f2caf923e185acb9d2da7b1e5 100644 (file)
@@ -764,6 +764,11 @@ PHP_FUNCTION(count)
                Z_PARAM_LONG(mode)
        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)) {
                case IS_NULL:
                        /* Intentionally not converted to an exception */
diff --git a/ext/standard/tests/array/count_invalid_mode.phpt b/ext/standard/tests/array/count_invalid_mode.phpt
new file mode 100644 (file)
index 0000000..6e302fd
--- /dev/null
@@ -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)
index 501b2cf598d0642667e669c6b8ce9d0f0725d32f..dd5c2342fca93e194a041490228ad56cf07f1ec1 100644 (file)
@@ -104,14 +104,10 @@ echo "\n-- Testing count() on arrays containing references --\n";
 $arr = array(1, array("a", "b", "c"));
 $arr[2] = &$arr[1];
 
-$mode_arr = array( COUNT_NORMAL, COUNT_RECURSIVE, 0, 1, -1, -1.45, 2, TRUE,
-                   FALSE, NULL);
-for( $i =0; $i < count( $mode_arr ); $i++) {
-  echo "For mode '$mode_arr[$i]' count is => ";
-  var_dump(count($arr, $mode_arr[$i]));
-}
-
-echo "\nDone";
+echo "Count normal" . \PHP_EOL;
+var_dump(count($arr, COUNT_NORMAL));
+echo "Count recursive" . \PHP_EOL;
+var_dump(count($arr, COUNT_RECURSIVE));
 
 /* closing the resource handles */
 fclose( $resource1 );
@@ -209,15 +205,7 @@ COUNT_NORMAL: should be 3, is 3
 int(2)
 
 -- Testing count() on arrays containing references --
-For mode '0' count is => int(3)
-For mode '1' count is => int(9)
-For mode '0' count is => int(3)
-For mode '1' count is => 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
+Count normal
+int(3)
+Count recursive
+int(9)