1<?php
2/**
3 * Input validation utilities.
4 *
5 * @package Requests\Utilities
6 */
7
8namespace WpOrg\Requests\Utility;
9
10use ArrayAccess;
11use CurlHandle;
12use Traversable;
13
14/**
15 * Input validation utilities.
16 *
17 * @package Requests\Utilities
18 */
19final class InputValidator {
20
21 /**
22 * Verify that a received input parameter is of type string or is "stringable".
23 *
24 * @param mixed $input Input parameter to verify.
25 *
26 * @return bool
27 */
28 public static function is_string_or_stringable($input) {
29 return is_string($input) || self::is_stringable_object($input);
30 }
31
32 /**
33 * Verify whether a received input parameter is usable as an integer array key.
34 *
35 * @param mixed $input Input parameter to verify.
36 *
37 * @return bool
38 */
39 public static function is_numeric_array_key($input) {
40 if (is_int($input)) {
41 return true;
42 }
43
44 if (!is_string($input)) {
45 return false;
46 }
47
48 return (bool) preg_match('`^-?[0-9]+$`', $input);
49 }
50
51 /**
52 * Verify whether a received input parameter is "stringable".
53 *
54 * @param mixed $input Input parameter to verify.
55 *
56 * @return bool
57 */
58 public static function is_stringable_object($input) {
59 return is_object($input) && method_exists($input, '__toString');
60 }
61
62 /**
63 * Verify whether a received input parameter is _accessible as if it were an array_.
64 *
65 * @param mixed $input Input parameter to verify.
66 *
67 * @return bool
68 */
69 public static function has_array_access($input) {
70 return is_array($input) || $input instanceof ArrayAccess;
71 }
72
73 /**
74 * Verify whether a received input parameter is "iterable".
75 *
76 * @internal The PHP native `is_iterable()` function was only introduced in PHP 7.1
77 * and this library still supports PHP 5.6.
78 *
79 * @param mixed $input Input parameter to verify.
80 *
81 * @return bool
82 */
83 public static function is_iterable($input) {
84 return is_array($input) || $input instanceof Traversable;
85 }
86
87 /**
88 * Verify whether a received input parameter is a Curl handle.
89 *
90 * The PHP Curl extension worked with resources prior to PHP 8.0 and with
91 * an instance of the `CurlHandle` class since PHP 8.0.
92 * {@link https://www.php.net/manual/en/migration80.incompatible.php#migration80.incompatible.resource2object}
93 *
94 * @param mixed $input Input parameter to verify.
95 *
96 * @return bool
97 */
98 public static function is_curl_handle($input) {
99 if (is_resource($input)) {
100 return get_resource_type($input) === 'curl';
101 }
102
103 if (is_object($input)) {
104 return $input instanceof CurlHandle;
105 }
106
107 return false;
108 }
109}
110