Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

855 lines
31KB

  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\helpers;
  8. use Yii;
  9. use yii\base\Arrayable;
  10. use yii\base\InvalidParamException;
  11. /**
  12. * BaseArrayHelper provides concrete implementation for [[ArrayHelper]].
  13. *
  14. * Do not use BaseArrayHelper. Use [[ArrayHelper]] instead.
  15. *
  16. * @author Qiang Xue <qiang.xue@gmail.com>
  17. * @since 2.0
  18. */
  19. class BaseArrayHelper
  20. {
  21. /**
  22. * Converts an object or an array of objects into an array.
  23. * @param object|array|string $object the object to be converted into an array
  24. * @param array $properties a mapping from object class names to the properties that need to put into the resulting arrays.
  25. * The properties specified for each class is an array of the following format:
  26. *
  27. * ```php
  28. * [
  29. * 'app\models\Post' => [
  30. * 'id',
  31. * 'title',
  32. * // the key name in array result => property name
  33. * 'createTime' => 'created_at',
  34. * // the key name in array result => anonymous function
  35. * 'length' => function ($post) {
  36. * return strlen($post->content);
  37. * },
  38. * ],
  39. * ]
  40. * ```
  41. *
  42. * The result of `ArrayHelper::toArray($post, $properties)` could be like the following:
  43. *
  44. * ```php
  45. * [
  46. * 'id' => 123,
  47. * 'title' => 'test',
  48. * 'createTime' => '2013-01-01 12:00AM',
  49. * 'length' => 301,
  50. * ]
  51. * ```
  52. *
  53. * @param boolean $recursive whether to recursively converts properties which are objects into arrays.
  54. * @return array the array representation of the object
  55. */
  56. public static function toArray($object, $properties = [], $recursive = true)
  57. {
  58. if (is_array($object)) {
  59. if ($recursive) {
  60. foreach ($object as $key => $value) {
  61. if (is_array($value) || is_object($value)) {
  62. $object[$key] = static::toArray($value, $properties, true);
  63. }
  64. }
  65. }
  66. return $object;
  67. } elseif (is_object($object)) {
  68. if (!empty($properties)) {
  69. $className = get_class($object);
  70. if (!empty($properties[$className])) {
  71. $result = [];
  72. foreach ($properties[$className] as $key => $name) {
  73. if (is_int($key)) {
  74. $result[$name] = $object->$name;
  75. } else {
  76. $result[$key] = static::getValue($object, $name);
  77. }
  78. }
  79. return $recursive ? static::toArray($result, $properties) : $result;
  80. }
  81. }
  82. if ($object instanceof Arrayable) {
  83. $result = $object->toArray([], [], $recursive);
  84. } else {
  85. $result = [];
  86. foreach ($object as $key => $value) {
  87. $result[$key] = $value;
  88. }
  89. }
  90. return $recursive ? static::toArray($result, $properties) : $result;
  91. } else {
  92. return [$object];
  93. }
  94. }
  95. /**
  96. * Merges two or more arrays into one recursively.
  97. * If each array has an element with the same string key value, the latter
  98. * will overwrite the former (different from array_merge_recursive).
  99. * Recursive merging will be conducted if both arrays have an element of array
  100. * type and are having the same key.
  101. * For integer-keyed elements, the elements from the latter array will
  102. * be appended to the former array.
  103. * You can use [[UnsetArrayValue]] object to unset value from previous array or
  104. * [[ReplaceArrayValue]] to force replace former value instead of recursive merging.
  105. * @param array $a array to be merged to
  106. * @param array $b array to be merged from. You can specify additional
  107. * arrays via third argument, fourth argument etc.
  108. * @return array the merged array (the original arrays are not changed.)
  109. */
  110. public static function merge($a, $b)
  111. {
  112. $args = func_get_args();
  113. $res = array_shift($args);
  114. while (!empty($args)) {
  115. $next = array_shift($args);
  116. foreach ($next as $k => $v) {
  117. if ($v instanceof UnsetArrayValue) {
  118. unset($res[$k]);
  119. } elseif ($v instanceof ReplaceArrayValue) {
  120. $res[$k] = $v->value;
  121. } elseif (is_int($k)) {
  122. if (isset($res[$k])) {
  123. $res[] = $v;
  124. } else {
  125. $res[$k] = $v;
  126. }
  127. } elseif (is_array($v) && isset($res[$k]) && is_array($res[$k])) {
  128. $res[$k] = self::merge($res[$k], $v);
  129. } else {
  130. $res[$k] = $v;
  131. }
  132. }
  133. }
  134. return $res;
  135. }
  136. /**
  137. * Retrieves the value of an array element or object property with the given key or property name.
  138. * If the key does not exist in the array or object, the default value will be returned instead.
  139. *
  140. * The key may be specified in a dot format to retrieve the value of a sub-array or the property
  141. * of an embedded object. In particular, if the key is `x.y.z`, then the returned value would
  142. * be `$array['x']['y']['z']` or `$array->x->y->z` (if `$array` is an object). If `$array['x']`
  143. * or `$array->x` is neither an array nor an object, the default value will be returned.
  144. * Note that if the array already has an element `x.y.z`, then its value will be returned
  145. * instead of going through the sub-arrays. So it is better to be done specifying an array of key names
  146. * like `['x', 'y', 'z']`.
  147. *
  148. * Below are some usage examples,
  149. *
  150. * ```php
  151. * // working with array
  152. * $username = \yii\helpers\ArrayHelper::getValue($_POST, 'username');
  153. * // working with object
  154. * $username = \yii\helpers\ArrayHelper::getValue($user, 'username');
  155. * // working with anonymous function
  156. * $fullName = \yii\helpers\ArrayHelper::getValue($user, function ($user, $defaultValue) {
  157. * return $user->firstName . ' ' . $user->lastName;
  158. * });
  159. * // using dot format to retrieve the property of embedded object
  160. * $street = \yii\helpers\ArrayHelper::getValue($users, 'address.street');
  161. * // using an array of keys to retrieve the value
  162. * $value = \yii\helpers\ArrayHelper::getValue($versions, ['1.0', 'date']);
  163. * ```
  164. *
  165. * @param array|object $array array or object to extract value from
  166. * @param string|\Closure|array $key key name of the array element, an array of keys or property name of the object,
  167. * or an anonymous function returning the value. The anonymous function signature should be:
  168. * `function($array, $defaultValue)`.
  169. * The possibility to pass an array of keys is available since version 2.0.4.
  170. * @param mixed $default the default value to be returned if the specified array key does not exist. Not used when
  171. * getting value from an object.
  172. * @return mixed the value of the element if found, default value otherwise
  173. * @throws InvalidParamException if $array is neither an array nor an object.
  174. */
  175. public static function getValue($array, $key, $default = null)
  176. {
  177. if ($key instanceof \Closure) {
  178. return $key($array, $default);
  179. }
  180. if (is_array($key)) {
  181. $lastKey = array_pop($key);
  182. foreach ($key as $keyPart) {
  183. $array = static::getValue($array, $keyPart);
  184. }
  185. $key = $lastKey;
  186. }
  187. if (is_array($array) && (isset($array[$key]) || array_key_exists($key, $array)) ) {
  188. return $array[$key];
  189. }
  190. if (($pos = strrpos($key, '.')) !== false) {
  191. $array = static::getValue($array, substr($key, 0, $pos), $default);
  192. $key = substr($key, $pos + 1);
  193. }
  194. if (is_object($array)) {
  195. // this is expected to fail if the property does not exist, or __get() is not implemented
  196. // it is not reliably possible to check whether a property is accessable beforehand
  197. return $array->$key;
  198. } elseif (is_array($array)) {
  199. return (isset($array[$key]) || array_key_exists($key, $array)) ? $array[$key] : $default;
  200. } else {
  201. return $default;
  202. }
  203. }
  204. /**
  205. * Removes an item from an array and returns the value. If the key does not exist in the array, the default value
  206. * will be returned instead.
  207. *
  208. * Usage examples,
  209. *
  210. * ```php
  211. * // $array = ['type' => 'A', 'options' => [1, 2]];
  212. * // working with array
  213. * $type = \yii\helpers\ArrayHelper::remove($array, 'type');
  214. * // $array content
  215. * // $array = ['options' => [1, 2]];
  216. * ```
  217. *
  218. * @param array $array the array to extract value from
  219. * @param string $key key name of the array element
  220. * @param mixed $default the default value to be returned if the specified key does not exist
  221. * @return mixed|null the value of the element if found, default value otherwise
  222. */
  223. public static function remove(&$array, $key, $default = null)
  224. {
  225. if (is_array($array) && (isset($array[$key]) || array_key_exists($key, $array))) {
  226. $value = $array[$key];
  227. unset($array[$key]);
  228. return $value;
  229. }
  230. return $default;
  231. }
  232. /**
  233. * Indexes and/or groups the array according to a specified key.
  234. * The input should be either multidimensional array or an array of objects.
  235. *
  236. * The $key can be either a key name of the sub-array, a property name of object, or an anonymous
  237. * function that must return the value that will be used as a key.
  238. *
  239. * $groups is an array of keys, that will be used to group the input array into one or more sub-arrays based
  240. * on keys specified.
  241. *
  242. * If the `$key` is specified as `null` or a value of an element corresponding to the key is `null` in addition
  243. * to `$groups` not specified then the element is discarded.
  244. *
  245. * For example:
  246. *
  247. * ```php
  248. * $array = [
  249. * ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
  250. * ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
  251. * ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
  252. * ];
  253. * $result = ArrayHelper::index($array, 'id');
  254. * ```
  255. *
  256. * The result will be an associative array, where the key is the value of `id` attribute
  257. *
  258. * ```php
  259. * [
  260. * '123' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
  261. * '345' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
  262. * // The second element of an original array is overwritten by the last element because of the same id
  263. * ]
  264. * ```
  265. *
  266. * An anonymous function can be used in the grouping array as well.
  267. *
  268. * ```php
  269. * $result = ArrayHelper::index($array, function ($element) {
  270. * return $element['id'];
  271. * });
  272. * ```
  273. *
  274. * Passing `id` as a third argument will group `$array` by `id`:
  275. *
  276. * ```php
  277. * $result = ArrayHelper::index($array, null, 'id');
  278. * ```
  279. *
  280. * The result will be a multidimensional array grouped by `id` on the first level, by `device` on the second level
  281. * and indexed by `data` on the third level:
  282. *
  283. * ```php
  284. * [
  285. * '123' => [
  286. * ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
  287. * ],
  288. * '345' => [ // all elements with this index are present in the result array
  289. * ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
  290. * ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
  291. * ]
  292. * ]
  293. * ```
  294. *
  295. * The anonymous function can be used in the array of grouping keys as well:
  296. *
  297. * ```php
  298. * $result = ArrayHelper::index($array, 'data', [function ($element) {
  299. * return $element['id'];
  300. * }, 'device']);
  301. * ```
  302. *
  303. * The result will be a multidimensional array grouped by `id` on the first level, by the `device` on the second one
  304. * and indexed by the `data` on the third level:
  305. *
  306. * ```php
  307. * [
  308. * '123' => [
  309. * 'laptop' => [
  310. * 'abc' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
  311. * ]
  312. * ],
  313. * '345' => [
  314. * 'tablet' => [
  315. * 'def' => ['id' => '345', 'data' => 'def', 'device' => 'tablet']
  316. * ],
  317. * 'smartphone' => [
  318. * 'hgi' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
  319. * ]
  320. * ]
  321. * ]
  322. * ```
  323. *
  324. * @param array $array the array that needs to be indexed or grouped
  325. * @param string|\Closure|null $key the column name or anonymous function which result will be used to index the array
  326. * @param string|string[]|\Closure[]|null $groups the array of keys, that will be used to group the input array
  327. * by one or more keys. If the $key attribute or its value for the particular element is null and $groups is not
  328. * defined, the array element will be discarded. Otherwise, if $groups is specified, array element will be added
  329. * to the result array without any key. This parameter is available since version 2.0.8.
  330. * @return array the indexed and/or grouped array
  331. */
  332. public static function index($array, $key, $groups = [])
  333. {
  334. $result = [];
  335. $groups = (array)$groups;
  336. foreach ($array as $element) {
  337. $lastArray = &$result;
  338. foreach ($groups as $group) {
  339. $value = static::getValue($element, $group);
  340. if (!array_key_exists($value, $lastArray)) {
  341. $lastArray[$value] = [];
  342. }
  343. $lastArray = &$lastArray[$value];
  344. }
  345. if ($key === null) {
  346. if (!empty($groups)) {
  347. $lastArray[] = $element;
  348. }
  349. } else {
  350. $value = static::getValue($element, $key);
  351. if ($value !== null) {
  352. if (is_float($value)) {
  353. $value = (string) $value;
  354. }
  355. $lastArray[$value] = $element;
  356. }
  357. }
  358. unset($lastArray);
  359. }
  360. return $result;
  361. }
  362. /**
  363. * Returns the values of a specified column in an array.
  364. * The input array should be multidimensional or an array of objects.
  365. *
  366. * For example,
  367. *
  368. * ```php
  369. * $array = [
  370. * ['id' => '123', 'data' => 'abc'],
  371. * ['id' => '345', 'data' => 'def'],
  372. * ];
  373. * $result = ArrayHelper::getColumn($array, 'id');
  374. * // the result is: ['123', '345']
  375. *
  376. * // using anonymous function
  377. * $result = ArrayHelper::getColumn($array, function ($element) {
  378. * return $element['id'];
  379. * });
  380. * ```
  381. *
  382. * @param array $array
  383. * @param string|\Closure $name
  384. * @param boolean $keepKeys whether to maintain the array keys. If false, the resulting array
  385. * will be re-indexed with integers.
  386. * @return array the list of column values
  387. */
  388. public static function getColumn($array, $name, $keepKeys = true)
  389. {
  390. $result = [];
  391. if ($keepKeys) {
  392. foreach ($array as $k => $element) {
  393. $result[$k] = static::getValue($element, $name);
  394. }
  395. } else {
  396. foreach ($array as $element) {
  397. $result[] = static::getValue($element, $name);
  398. }
  399. }
  400. return $result;
  401. }
  402. /**
  403. * Builds a map (key-value pairs) from a multidimensional array or an array of objects.
  404. * The `$from` and `$to` parameters specify the key names or property names to set up the map.
  405. * Optionally, one can further group the map according to a grouping field `$group`.
  406. *
  407. * For example,
  408. *
  409. * ```php
  410. * $array = [
  411. * ['id' => '123', 'name' => 'aaa', 'class' => 'x'],
  412. * ['id' => '124', 'name' => 'bbb', 'class' => 'x'],
  413. * ['id' => '345', 'name' => 'ccc', 'class' => 'y'],
  414. * ];
  415. *
  416. * $result = ArrayHelper::map($array, 'id', 'name');
  417. * // the result is:
  418. * // [
  419. * // '123' => 'aaa',
  420. * // '124' => 'bbb',
  421. * // '345' => 'ccc',
  422. * // ]
  423. *
  424. * $result = ArrayHelper::map($array, 'id', 'name', 'class');
  425. * // the result is:
  426. * // [
  427. * // 'x' => [
  428. * // '123' => 'aaa',
  429. * // '124' => 'bbb',
  430. * // ],
  431. * // 'y' => [
  432. * // '345' => 'ccc',
  433. * // ],
  434. * // ]
  435. * ```
  436. *
  437. * @param array $array
  438. * @param string|\Closure $from
  439. * @param string|\Closure $to
  440. * @param string|\Closure $group
  441. * @return array
  442. */
  443. public static function map($array, $from, $to, $group = null)
  444. {
  445. $result = [];
  446. foreach ($array as $element) {
  447. $key = static::getValue($element, $from);
  448. $value = static::getValue($element, $to);
  449. if ($group !== null) {
  450. $result[static::getValue($element, $group)][$key] = $value;
  451. } else {
  452. $result[$key] = $value;
  453. }
  454. }
  455. return $result;
  456. }
  457. /**
  458. * Checks if the given array contains the specified key.
  459. * This method enhances the `array_key_exists()` function by supporting case-insensitive
  460. * key comparison.
  461. * @param string $key the key to check
  462. * @param array $array the array with keys to check
  463. * @param boolean $caseSensitive whether the key comparison should be case-sensitive
  464. * @return boolean whether the array contains the specified key
  465. */
  466. public static function keyExists($key, $array, $caseSensitive = true)
  467. {
  468. if ($caseSensitive) {
  469. // Function `isset` checks key faster but skips `null`, `array_key_exists` handles this case
  470. // http://php.net/manual/en/function.array-key-exists.php#107786
  471. return isset($array[$key]) || array_key_exists($key, $array);
  472. } else {
  473. foreach (array_keys($array) as $k) {
  474. if (strcasecmp($key, $k) === 0) {
  475. return true;
  476. }
  477. }
  478. return false;
  479. }
  480. }
  481. /**
  482. * Sorts an array of objects or arrays (with the same structure) by one or several keys.
  483. * @param array $array the array to be sorted. The array will be modified after calling this method.
  484. * @param string|\Closure|array $key the key(s) to be sorted by. This refers to a key name of the sub-array
  485. * elements, a property name of the objects, or an anonymous function returning the values for comparison
  486. * purpose. The anonymous function signature should be: `function($item)`.
  487. * To sort by multiple keys, provide an array of keys here.
  488. * @param integer|array $direction the sorting direction. It can be either `SORT_ASC` or `SORT_DESC`.
  489. * When sorting by multiple keys with different sorting directions, use an array of sorting directions.
  490. * @param integer|array $sortFlag the PHP sort flag. Valid values include
  491. * `SORT_REGULAR`, `SORT_NUMERIC`, `SORT_STRING`, `SORT_LOCALE_STRING`, `SORT_NATURAL` and `SORT_FLAG_CASE`.
  492. * Please refer to [PHP manual](http://php.net/manual/en/function.sort.php)
  493. * for more details. When sorting by multiple keys with different sort flags, use an array of sort flags.
  494. * @throws InvalidParamException if the $direction or $sortFlag parameters do not have
  495. * correct number of elements as that of $key.
  496. */
  497. public static function multisort(&$array, $key, $direction = SORT_ASC, $sortFlag = SORT_REGULAR)
  498. {
  499. $keys = is_array($key) ? $key : [$key];
  500. if (empty($keys) || empty($array)) {
  501. return;
  502. }
  503. $n = count($keys);
  504. if (is_scalar($direction)) {
  505. $direction = array_fill(0, $n, $direction);
  506. } elseif (count($direction) !== $n) {
  507. throw new InvalidParamException('The length of $direction parameter must be the same as that of $keys.');
  508. }
  509. if (is_scalar($sortFlag)) {
  510. $sortFlag = array_fill(0, $n, $sortFlag);
  511. } elseif (count($sortFlag) !== $n) {
  512. throw new InvalidParamException('The length of $sortFlag parameter must be the same as that of $keys.');
  513. }
  514. $args = [];
  515. foreach ($keys as $i => $key) {
  516. $flag = $sortFlag[$i];
  517. $args[] = static::getColumn($array, $key);
  518. $args[] = $direction[$i];
  519. $args[] = $flag;
  520. }
  521. // This fix is used for cases when main sorting specified by columns has equal values
  522. // Without it it will lead to Fatal Error: Nesting level too deep - recursive dependency?
  523. $args[] = range(1, count($array));
  524. $args[] = SORT_ASC;
  525. $args[] = SORT_NUMERIC;
  526. $args[] = &$array;
  527. call_user_func_array('array_multisort', $args);
  528. }
  529. /**
  530. * Encodes special characters in an array of strings into HTML entities.
  531. * Only array values will be encoded by default.
  532. * If a value is an array, this method will also encode it recursively.
  533. * Only string values will be encoded.
  534. * @param array $data data to be encoded
  535. * @param boolean $valuesOnly whether to encode array values only. If false,
  536. * both the array keys and array values will be encoded.
  537. * @param string $charset the charset that the data is using. If not set,
  538. * [[\yii\base\Application::charset]] will be used.
  539. * @return array the encoded data
  540. * @see http://www.php.net/manual/en/function.htmlspecialchars.php
  541. */
  542. public static function htmlEncode($data, $valuesOnly = true, $charset = null)
  543. {
  544. if ($charset === null) {
  545. $charset = Yii::$app ? Yii::$app->charset : 'UTF-8';
  546. }
  547. $d = [];
  548. foreach ($data as $key => $value) {
  549. if (!$valuesOnly && is_string($key)) {
  550. $key = htmlspecialchars($key, ENT_QUOTES | ENT_SUBSTITUTE, $charset);
  551. }
  552. if (is_string($value)) {
  553. $d[$key] = htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, $charset);
  554. } elseif (is_array($value)) {
  555. $d[$key] = static::htmlEncode($value, $valuesOnly, $charset);
  556. } else {
  557. $d[$key] = $value;
  558. }
  559. }
  560. return $d;
  561. }
  562. /**
  563. * Decodes HTML entities into the corresponding characters in an array of strings.
  564. * Only array values will be decoded by default.
  565. * If a value is an array, this method will also decode it recursively.
  566. * Only string values will be decoded.
  567. * @param array $data data to be decoded
  568. * @param boolean $valuesOnly whether to decode array values only. If false,
  569. * both the array keys and array values will be decoded.
  570. * @return array the decoded data
  571. * @see http://www.php.net/manual/en/function.htmlspecialchars-decode.php
  572. */
  573. public static function htmlDecode($data, $valuesOnly = true)
  574. {
  575. $d = [];
  576. foreach ($data as $key => $value) {
  577. if (!$valuesOnly && is_string($key)) {
  578. $key = htmlspecialchars_decode($key, ENT_QUOTES);
  579. }
  580. if (is_string($value)) {
  581. $d[$key] = htmlspecialchars_decode($value, ENT_QUOTES);
  582. } elseif (is_array($value)) {
  583. $d[$key] = static::htmlDecode($value);
  584. } else {
  585. $d[$key] = $value;
  586. }
  587. }
  588. return $d;
  589. }
  590. /**
  591. * Returns a value indicating whether the given array is an associative array.
  592. *
  593. * An array is associative if all its keys are strings. If `$allStrings` is false,
  594. * then an array will be treated as associative if at least one of its keys is a string.
  595. *
  596. * Note that an empty array will NOT be considered associative.
  597. *
  598. * @param array $array the array being checked
  599. * @param boolean $allStrings whether the array keys must be all strings in order for
  600. * the array to be treated as associative.
  601. * @return boolean whether the array is associative
  602. */
  603. public static function isAssociative($array, $allStrings = true)
  604. {
  605. if (!is_array($array) || empty($array)) {
  606. return false;
  607. }
  608. if ($allStrings) {
  609. foreach ($array as $key => $value) {
  610. if (!is_string($key)) {
  611. return false;
  612. }
  613. }
  614. return true;
  615. } else {
  616. foreach ($array as $key => $value) {
  617. if (is_string($key)) {
  618. return true;
  619. }
  620. }
  621. return false;
  622. }
  623. }
  624. /**
  625. * Returns a value indicating whether the given array is an indexed array.
  626. *
  627. * An array is indexed if all its keys are integers. If `$consecutive` is true,
  628. * then the array keys must be a consecutive sequence starting from 0.
  629. *
  630. * Note that an empty array will be considered indexed.
  631. *
  632. * @param array $array the array being checked
  633. * @param boolean $consecutive whether the array keys must be a consecutive sequence
  634. * in order for the array to be treated as indexed.
  635. * @return boolean whether the array is associative
  636. */
  637. public static function isIndexed($array, $consecutive = false)
  638. {
  639. if (!is_array($array)) {
  640. return false;
  641. }
  642. if (empty($array)) {
  643. return true;
  644. }
  645. if ($consecutive) {
  646. return array_keys($array) === range(0, count($array) - 1);
  647. } else {
  648. foreach ($array as $key => $value) {
  649. if (!is_int($key)) {
  650. return false;
  651. }
  652. }
  653. return true;
  654. }
  655. }
  656. /**
  657. * Check whether an array or [[\Traversable]] contains an element.
  658. *
  659. * This method does the same as the PHP function [in_array()](http://php.net/manual/en/function.in-array.php)
  660. * but additionally works for objects that implement the [[\Traversable]] interface.
  661. * @param mixed $needle The value to look for.
  662. * @param array|\Traversable $haystack The set of values to search.
  663. * @param boolean $strict Whether to enable strict (`===`) comparison.
  664. * @return boolean `true` if `$needle` was found in `$haystack`, `false` otherwise.
  665. * @throws InvalidParamException if `$haystack` is neither traversable nor an array.
  666. * @see http://php.net/manual/en/function.in-array.php
  667. * @since 2.0.7
  668. */
  669. public static function isIn($needle, $haystack, $strict = false)
  670. {
  671. if ($haystack instanceof \Traversable) {
  672. foreach ($haystack as $value) {
  673. if ($needle == $value && (!$strict || $needle === $value)) {
  674. return true;
  675. }
  676. }
  677. } elseif (is_array($haystack)) {
  678. return in_array($needle, $haystack, $strict);
  679. } else {
  680. throw new InvalidParamException('Argument $haystack must be an array or implement Traversable');
  681. }
  682. return false;
  683. }
  684. /**
  685. * Checks whether a variable is an array or [[\Traversable]].
  686. *
  687. * This method does the same as the PHP function [is_array()](http://php.net/manual/en/function.is-array.php)
  688. * but additionally works on objects that implement the [[\Traversable]] interface.
  689. * @param mixed $var The variable being evaluated.
  690. * @return boolean whether $var is array-like
  691. * @see http://php.net/manual/en/function.is_array.php
  692. * @since 2.0.8
  693. */
  694. public static function isTraversable($var)
  695. {
  696. return is_array($var) || $var instanceof \Traversable;
  697. }
  698. /**
  699. * Checks whether an array or [[\Traversable]] is a subset of another array or [[\Traversable]].
  700. *
  701. * This method will return `true`, if all elements of `$needles` are contained in
  702. * `$haystack`. If at least one element is missing, `false` will be returned.
  703. * @param array|\Traversable $needles The values that must **all** be in `$haystack`.
  704. * @param array|\Traversable $haystack The set of value to search.
  705. * @param boolean $strict Whether to enable strict (`===`) comparison.
  706. * @throws InvalidParamException if `$haystack` or `$needles` is neither traversable nor an array.
  707. * @return boolean `true` if `$needles` is a subset of `$haystack`, `false` otherwise.
  708. * @since 2.0.7
  709. */
  710. public static function isSubset($needles, $haystack, $strict = false)
  711. {
  712. if (is_array($needles) || $needles instanceof \Traversable) {
  713. foreach ($needles as $needle) {
  714. if (!static::isIn($needle, $haystack, $strict)) {
  715. return false;
  716. }
  717. }
  718. return true;
  719. } else {
  720. throw new InvalidParamException('Argument $needles must be an array or implement Traversable');
  721. }
  722. }
  723. /**
  724. * Filters array according to rules specified.
  725. *
  726. * For example:
  727. *
  728. * ```php
  729. * $array = [
  730. * 'A' => [1, 2],
  731. * 'B' => [
  732. * 'C' => 1,
  733. * 'D' => 2,
  734. * ],
  735. * 'E' => 1,
  736. * ];
  737. *
  738. * $result = \yii\helpers\ArrayHelper::filter($array, ['A']);
  739. * // $result will be:
  740. * // [
  741. * // 'A' => [1, 2],
  742. * // ]
  743. *
  744. * $result = \yii\helpers\ArrayHelper::filter($array, ['A', 'B.C']);
  745. * // $result will be:
  746. * // [
  747. * // 'A' => [1, 2],
  748. * // 'B' => ['C' => 1],
  749. * // ]
  750. *
  751. * $result = \yii\helpers\ArrayHelper::filter($array, ['B', '!B.C']);
  752. * // $result will be:
  753. * // [
  754. * // 'B' => ['D' => 2],
  755. * // ]
  756. * ```
  757. *
  758. * @param array $array Source array
  759. * @param array $filters Rules that define array keys which should be left or removed from results.
  760. * Each rule is:
  761. * - `var` - `$array['var']` will be left in result.
  762. * - `var.key` = only `$array['var']['key'] will be left in result.
  763. * - `!var.key` = `$array['var']['key'] will be removed from result.
  764. * @return array Filtered array
  765. * @since 2.0.9
  766. */
  767. public static function filter($array, $filters)
  768. {
  769. $result = [];
  770. $forbiddenVars = [];
  771. foreach ($filters as $var) {
  772. $keys = explode('.', $var);
  773. $globalKey = $keys[0];
  774. $localKey = isset($keys[1]) ? $keys[1] : null;
  775. if ($globalKey[0] === '!') {
  776. $forbiddenVars[] = [
  777. substr($globalKey, 1),
  778. $localKey,
  779. ];
  780. continue;
  781. }
  782. if (empty($array[$globalKey])) {
  783. continue;
  784. }
  785. if ($localKey === null) {
  786. $result[$globalKey] = $array[$globalKey];
  787. continue;
  788. }
  789. if (!isset($array[$globalKey][$localKey])) {
  790. continue;
  791. }
  792. if (!array_key_exists($globalKey, $result)) {
  793. $result[$globalKey] = [];
  794. }
  795. $result[$globalKey][$localKey] = $array[$globalKey][$localKey];
  796. }
  797. foreach ($forbiddenVars as $var) {
  798. list($globalKey, $localKey) = $var;
  799. if (array_key_exists($globalKey, $result)) {
  800. unset($result[$globalKey][$localKey]);
  801. }
  802. }
  803. return $result;
  804. }
  805. }