ArrayUtils.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. <?php // phpcs:disable WebimpressCodingStandard.NamingConventions.AbstractClass.Prefix
  2. declare(strict_types=1);
  3. namespace Laminas\Stdlib;
  4. use Iterator;
  5. use Laminas\Stdlib\ArrayUtils\MergeRemoveKey;
  6. use Laminas\Stdlib\ArrayUtils\MergeReplaceKeyInterface;
  7. use Traversable;
  8. use function array_filter;
  9. use function array_key_exists;
  10. use function array_keys;
  11. use function array_values;
  12. use function in_array;
  13. use function is_array;
  14. use function is_callable;
  15. use function is_float;
  16. use function is_int;
  17. use function is_object;
  18. use function is_scalar;
  19. use function is_string;
  20. use function iterator_to_array;
  21. use function method_exists;
  22. use function sprintf;
  23. /**
  24. * Utility class for testing and manipulation of PHP arrays.
  25. *
  26. * Declared abstract, as we have no need for instantiation.
  27. */
  28. abstract class ArrayUtils
  29. {
  30. /**
  31. * Compatibility Flag for ArrayUtils::filter
  32. *
  33. * @deprecated
  34. */
  35. public const ARRAY_FILTER_USE_BOTH = 1;
  36. /**
  37. * Compatibility Flag for ArrayUtils::filter
  38. *
  39. * @deprecated
  40. */
  41. public const ARRAY_FILTER_USE_KEY = 2;
  42. /**
  43. * Test whether an array contains one or more string keys
  44. *
  45. * @param bool $allowEmpty Should an empty array() return true
  46. * @return bool
  47. */
  48. public static function hasStringKeys(mixed $value, $allowEmpty = false)
  49. {
  50. if (! is_array($value)) {
  51. return false;
  52. }
  53. if (! $value) {
  54. return $allowEmpty;
  55. }
  56. return [] !== array_filter(array_keys($value), 'is_string');
  57. }
  58. /**
  59. * Test whether an array contains one or more integer keys
  60. *
  61. * @param bool $allowEmpty Should an empty array() return true
  62. * @return bool
  63. */
  64. public static function hasIntegerKeys(mixed $value, $allowEmpty = false)
  65. {
  66. if (! is_array($value)) {
  67. return false;
  68. }
  69. if (! $value) {
  70. return $allowEmpty;
  71. }
  72. return [] !== array_filter(array_keys($value), 'is_int');
  73. }
  74. /**
  75. * Test whether an array contains one or more numeric keys.
  76. *
  77. * A numeric key can be one of the following:
  78. * - an integer 1,
  79. * - a string with a number '20'
  80. * - a string with negative number: '-1000'
  81. * - a float: 2.2120, -78.150999
  82. * - a string with float: '4000.99999', '-10.10'
  83. *
  84. * @param bool $allowEmpty Should an empty array() return true
  85. * @return bool
  86. */
  87. public static function hasNumericKeys(mixed $value, $allowEmpty = false)
  88. {
  89. if (! is_array($value)) {
  90. return false;
  91. }
  92. if (! $value) {
  93. return $allowEmpty;
  94. }
  95. return [] !== array_filter(array_keys($value), 'is_numeric');
  96. }
  97. /**
  98. * Test whether an array is a list
  99. *
  100. * A list is a collection of values assigned to continuous integer keys
  101. * starting at 0 and ending at count() - 1.
  102. *
  103. * For example:
  104. * <code>
  105. * $list = array('a', 'b', 'c', 'd');
  106. * $list = array(
  107. * 0 => 'foo',
  108. * 1 => 'bar',
  109. * 2 => array('foo' => 'baz'),
  110. * );
  111. * </code>
  112. *
  113. * @param bool $allowEmpty Is an empty list a valid list?
  114. * @return bool
  115. */
  116. public static function isList(mixed $value, $allowEmpty = false)
  117. {
  118. if (! is_array($value)) {
  119. return false;
  120. }
  121. if (! $value) {
  122. return $allowEmpty;
  123. }
  124. return array_values($value) === $value;
  125. }
  126. /**
  127. * Test whether an array is a hash table.
  128. *
  129. * An array is a hash table if:
  130. *
  131. * 1. Contains one or more non-integer keys, or
  132. * 2. Integer keys are non-continuous or misaligned (not starting with 0)
  133. *
  134. * For example:
  135. * <code>
  136. * $hash = array(
  137. * 'foo' => 15,
  138. * 'bar' => false,
  139. * );
  140. * $hash = array(
  141. * 1995 => 'Birth of PHP',
  142. * 2009 => 'PHP 5.3.0',
  143. * 2012 => 'PHP 5.4.0',
  144. * );
  145. * $hash = array(
  146. * 'formElement,
  147. * 'options' => array( 'debug' => true ),
  148. * );
  149. * </code>
  150. *
  151. * @param bool $allowEmpty Is an empty array() a valid hash table?
  152. * @return bool
  153. */
  154. public static function isHashTable(mixed $value, $allowEmpty = false)
  155. {
  156. if (! is_array($value)) {
  157. return false;
  158. }
  159. if (! $value) {
  160. return $allowEmpty;
  161. }
  162. return array_values($value) !== $value;
  163. }
  164. /**
  165. * Checks if a value exists in an array.
  166. *
  167. * Due to "foo" == 0 === TRUE with in_array when strict = false, an option
  168. * has been added to prevent this. When $strict = 0/false, the most secure
  169. * non-strict check is implemented. if $strict = -1, the default in_array
  170. * non-strict behaviour is used.
  171. *
  172. * @deprecated This method will be removed in version 4.0 of this component
  173. *
  174. * @param array $haystack
  175. * @param int|bool $strict
  176. * @return bool
  177. */
  178. public static function inArray(mixed $needle, array $haystack, $strict = false)
  179. {
  180. if ((bool) $strict === false) {
  181. if (is_int($needle) || is_float($needle)) {
  182. $needle = (string) $needle;
  183. }
  184. if (is_string($needle)) {
  185. foreach ($haystack as &$h) {
  186. if (is_int($h) || is_float($h)) {
  187. $h = (string) $h;
  188. }
  189. }
  190. }
  191. }
  192. return in_array($needle, $haystack, (bool) $strict);
  193. }
  194. /**
  195. * Converts an iterator to an array. The $recursive flag, on by default,
  196. * hints whether or not you want to do so recursively.
  197. *
  198. * @template TKey
  199. * @template TValue
  200. * @param iterable<TKey, TValue> $iterator The array or Traversable object to convert
  201. * @param bool $recursive Recursively check all nested structures
  202. * @throws Exception\InvalidArgumentException If $iterator is not an array or a Traversable object.
  203. * @return array<TKey, TValue>
  204. */
  205. public static function iteratorToArray($iterator, $recursive = true)
  206. {
  207. /** @psalm-suppress DocblockTypeContradiction */
  208. if (! is_array($iterator) && ! $iterator instanceof Traversable) {
  209. throw new Exception\InvalidArgumentException(__METHOD__ . ' expects an array or Traversable object');
  210. }
  211. if (! $recursive) {
  212. if (is_array($iterator)) {
  213. return $iterator;
  214. }
  215. return iterator_to_array($iterator);
  216. }
  217. if (
  218. is_object($iterator)
  219. && ! $iterator instanceof Iterator
  220. && method_exists($iterator, 'toArray')
  221. ) {
  222. /** @psalm-var array<TKey, TValue> $array */
  223. $array = $iterator->toArray();
  224. return $array;
  225. }
  226. $array = [];
  227. foreach ($iterator as $key => $value) {
  228. if (is_scalar($value)) {
  229. $array[$key] = $value;
  230. continue;
  231. }
  232. if ($value instanceof Traversable) {
  233. $array[$key] = static::iteratorToArray($value, $recursive);
  234. continue;
  235. }
  236. if (is_array($value)) {
  237. $array[$key] = static::iteratorToArray($value, $recursive);
  238. continue;
  239. }
  240. $array[$key] = $value;
  241. }
  242. /** @psalm-var array<TKey, TValue> $array */
  243. return $array;
  244. }
  245. /**
  246. * Merge two arrays together.
  247. *
  248. * If an integer key exists in both arrays and preserveNumericKeys is false, the value
  249. * from the second array will be appended to the first array. If both values are arrays, they
  250. * are merged together, else the value of the second array overwrites the one of the first array.
  251. *
  252. * @param array $a
  253. * @param array $b
  254. * @param bool $preserveNumericKeys
  255. * @return array
  256. */
  257. public static function merge(array $a, array $b, $preserveNumericKeys = false)
  258. {
  259. foreach ($b as $key => $value) {
  260. if ($value instanceof MergeReplaceKeyInterface) {
  261. $a[$key] = $value->getData();
  262. } elseif (isset($a[$key]) || array_key_exists($key, $a)) {
  263. if ($value instanceof MergeRemoveKey) {
  264. unset($a[$key]);
  265. } elseif (! $preserveNumericKeys && is_int($key)) {
  266. $a[] = $value;
  267. } elseif (is_array($value) && is_array($a[$key])) {
  268. $a[$key] = static::merge($a[$key], $value, $preserveNumericKeys);
  269. } else {
  270. $a[$key] = $value;
  271. }
  272. } else {
  273. if (! $value instanceof MergeRemoveKey) {
  274. $a[$key] = $value;
  275. }
  276. }
  277. }
  278. return $a;
  279. }
  280. /**
  281. * @deprecated Since 3.2.0; use the native array_filter methods
  282. *
  283. * @param callable $callback
  284. * @param null|int $flag
  285. * @return array
  286. * @throws Exception\InvalidArgumentException
  287. */
  288. public static function filter(array $data, $callback, $flag = null)
  289. {
  290. if (! is_callable($callback)) {
  291. throw new Exception\InvalidArgumentException(sprintf(
  292. 'Second parameter of %s must be callable',
  293. __METHOD__
  294. ));
  295. }
  296. return array_filter($data, $callback, $flag ?? 0);
  297. }
  298. }