BaseArrayHelper.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  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 bool $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. */
  174. public static function getValue($array, $key, $default = null)
  175. {
  176. if ($key instanceof \Closure) {
  177. return $key($array, $default);
  178. }
  179. if (is_array($key)) {
  180. $lastKey = array_pop($key);
  181. foreach ($key as $keyPart) {
  182. $array = static::getValue($array, $keyPart);
  183. }
  184. $key = $lastKey;
  185. }
  186. if (is_array($array) && (isset($array[$key]) || array_key_exists($key, $array)) ) {
  187. return $array[$key];
  188. }
  189. if (($pos = strrpos($key, '.')) !== false) {
  190. $array = static::getValue($array, substr($key, 0, $pos), $default);
  191. $key = substr($key, $pos + 1);
  192. }
  193. if (is_object($array)) {
  194. // this is expected to fail if the property does not exist, or __get() is not implemented
  195. // it is not reliably possible to check whether a property is accessible beforehand
  196. return $array->$key;
  197. } elseif (is_array($array)) {
  198. return (isset($array[$key]) || array_key_exists($key, $array)) ? $array[$key] : $default;
  199. } else {
  200. return $default;
  201. }
  202. }
  203. /**
  204. * Removes an item from an array and returns the value. If the key does not exist in the array, the default value
  205. * will be returned instead.
  206. *
  207. * Usage examples,
  208. *
  209. * ```php
  210. * // $array = ['type' => 'A', 'options' => [1, 2]];
  211. * // working with array
  212. * $type = \yii\helpers\ArrayHelper::remove($array, 'type');
  213. * // $array content
  214. * // $array = ['options' => [1, 2]];
  215. * ```
  216. *
  217. * @param array $array the array to extract value from
  218. * @param string $key key name of the array element
  219. * @param mixed $default the default value to be returned if the specified key does not exist
  220. * @return mixed|null the value of the element if found, default value otherwise
  221. */
  222. public static function remove(&$array, $key, $default = null)
  223. {
  224. if (is_array($array) && (isset($array[$key]) || array_key_exists($key, $array))) {
  225. $value = $array[$key];
  226. unset($array[$key]);
  227. return $value;
  228. }
  229. return $default;
  230. }
  231. /**
  232. * Removes items with matching values from the array and returns the removed items.
  233. *
  234. * Example,
  235. *
  236. * ```php
  237. * $array = ['Bob' => 'Dylan', 'Michael' => 'Jackson', 'Mick' => 'Jagger', 'Janet' => 'Jackson'];
  238. * $removed = \yii\helpers\ArrayHelper::removeValue($array, 'Jackson');
  239. * // result:
  240. * // $array = ['Bob' => 'Dylan', 'Mick' => 'Jagger'];
  241. * // $removed = ['Michael' => 'Jackson', 'Janet' => 'Jackson'];
  242. * ```
  243. *
  244. * @param array $array the array where to look the value from
  245. * @param string $value the value to remove from the array
  246. * @return array the items that were removed from the array
  247. * @since 2.0.11
  248. */
  249. public static function removeValue(&$array, $value)
  250. {
  251. $result = [];
  252. if (is_array($array)) {
  253. foreach ($array as $key => $val) {
  254. if ($val === $value) {
  255. $result[$key] = $val;
  256. unset($array[$key]);
  257. }
  258. }
  259. }
  260. return $result;
  261. }
  262. /**
  263. * Indexes and/or groups the array according to a specified key.
  264. * The input should be either multidimensional array or an array of objects.
  265. *
  266. * The $key can be either a key name of the sub-array, a property name of object, or an anonymous
  267. * function that must return the value that will be used as a key.
  268. *
  269. * $groups is an array of keys, that will be used to group the input array into one or more sub-arrays based
  270. * on keys specified.
  271. *
  272. * If the `$key` is specified as `null` or a value of an element corresponding to the key is `null` in addition
  273. * to `$groups` not specified then the element is discarded.
  274. *
  275. * For example:
  276. *
  277. * ```php
  278. * $array = [
  279. * ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
  280. * ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
  281. * ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
  282. * ];
  283. * $result = ArrayHelper::index($array, 'id');
  284. * ```
  285. *
  286. * The result will be an associative array, where the key is the value of `id` attribute
  287. *
  288. * ```php
  289. * [
  290. * '123' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
  291. * '345' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
  292. * // The second element of an original array is overwritten by the last element because of the same id
  293. * ]
  294. * ```
  295. *
  296. * An anonymous function can be used in the grouping array as well.
  297. *
  298. * ```php
  299. * $result = ArrayHelper::index($array, function ($element) {
  300. * return $element['id'];
  301. * });
  302. * ```
  303. *
  304. * Passing `id` as a third argument will group `$array` by `id`:
  305. *
  306. * ```php
  307. * $result = ArrayHelper::index($array, null, 'id');
  308. * ```
  309. *
  310. * The result will be a multidimensional array grouped by `id` on the first level, by `device` on the second level
  311. * and indexed by `data` on the third level:
  312. *
  313. * ```php
  314. * [
  315. * '123' => [
  316. * ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
  317. * ],
  318. * '345' => [ // all elements with this index are present in the result array
  319. * ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
  320. * ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
  321. * ]
  322. * ]
  323. * ```
  324. *
  325. * The anonymous function can be used in the array of grouping keys as well:
  326. *
  327. * ```php
  328. * $result = ArrayHelper::index($array, 'data', [function ($element) {
  329. * return $element['id'];
  330. * }, 'device']);
  331. * ```
  332. *
  333. * The result will be a multidimensional array grouped by `id` on the first level, by the `device` on the second one
  334. * and indexed by the `data` on the third level:
  335. *
  336. * ```php
  337. * [
  338. * '123' => [
  339. * 'laptop' => [
  340. * 'abc' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
  341. * ]
  342. * ],
  343. * '345' => [
  344. * 'tablet' => [
  345. * 'def' => ['id' => '345', 'data' => 'def', 'device' => 'tablet']
  346. * ],
  347. * 'smartphone' => [
  348. * 'hgi' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
  349. * ]
  350. * ]
  351. * ]
  352. * ```
  353. *
  354. * @param array $array the array that needs to be indexed or grouped
  355. * @param string|\Closure|null $key the column name or anonymous function which result will be used to index the array
  356. * @param string|string[]|\Closure[]|null $groups the array of keys, that will be used to group the input array
  357. * by one or more keys. If the $key attribute or its value for the particular element is null and $groups is not
  358. * defined, the array element will be discarded. Otherwise, if $groups is specified, array element will be added
  359. * to the result array without any key. This parameter is available since version 2.0.8.
  360. * @return array the indexed and/or grouped array
  361. */
  362. public static function index($array, $key, $groups = [])
  363. {
  364. $result = [];
  365. $groups = (array)$groups;
  366. foreach ($array as $element) {
  367. $lastArray = &$result;
  368. foreach ($groups as $group) {
  369. $value = static::getValue($element, $group);
  370. if (!array_key_exists($value, $lastArray)) {
  371. $lastArray[$value] = [];
  372. }
  373. $lastArray = &$lastArray[$value];
  374. }
  375. if ($key === null) {
  376. if (!empty($groups)) {
  377. $lastArray[] = $element;
  378. }
  379. } else {
  380. $value = static::getValue($element, $key);
  381. if ($value !== null) {
  382. if (is_float($value)) {
  383. $value = (string) $value;
  384. }
  385. $lastArray[$value] = $element;
  386. }
  387. }
  388. unset($lastArray);
  389. }
  390. return $result;
  391. }
  392. /**
  393. * Returns the values of a specified column in an array.
  394. * The input array should be multidimensional or an array of objects.
  395. *
  396. * For example,
  397. *
  398. * ```php
  399. * $array = [
  400. * ['id' => '123', 'data' => 'abc'],
  401. * ['id' => '345', 'data' => 'def'],
  402. * ];
  403. * $result = ArrayHelper::getColumn($array, 'id');
  404. * // the result is: ['123', '345']
  405. *
  406. * // using anonymous function
  407. * $result = ArrayHelper::getColumn($array, function ($element) {
  408. * return $element['id'];
  409. * });
  410. * ```
  411. *
  412. * @param array $array
  413. * @param string|\Closure $name
  414. * @param bool $keepKeys whether to maintain the array keys. If false, the resulting array
  415. * will be re-indexed with integers.
  416. * @return array the list of column values
  417. */
  418. public static function getColumn($array, $name, $keepKeys = true)
  419. {
  420. $result = [];
  421. if ($keepKeys) {
  422. foreach ($array as $k => $element) {
  423. $result[$k] = static::getValue($element, $name);
  424. }
  425. } else {
  426. foreach ($array as $element) {
  427. $result[] = static::getValue($element, $name);
  428. }
  429. }
  430. return $result;
  431. }
  432. /**
  433. * Builds a map (key-value pairs) from a multidimensional array or an array of objects.
  434. * The `$from` and `$to` parameters specify the key names or property names to set up the map.
  435. * Optionally, one can further group the map according to a grouping field `$group`.
  436. *
  437. * For example,
  438. *
  439. * ```php
  440. * $array = [
  441. * ['id' => '123', 'name' => 'aaa', 'class' => 'x'],
  442. * ['id' => '124', 'name' => 'bbb', 'class' => 'x'],
  443. * ['id' => '345', 'name' => 'ccc', 'class' => 'y'],
  444. * ];
  445. *
  446. * $result = ArrayHelper::map($array, 'id', 'name');
  447. * // the result is:
  448. * // [
  449. * // '123' => 'aaa',
  450. * // '124' => 'bbb',
  451. * // '345' => 'ccc',
  452. * // ]
  453. *
  454. * $result = ArrayHelper::map($array, 'id', 'name', 'class');
  455. * // the result is:
  456. * // [
  457. * // 'x' => [
  458. * // '123' => 'aaa',
  459. * // '124' => 'bbb',
  460. * // ],
  461. * // 'y' => [
  462. * // '345' => 'ccc',
  463. * // ],
  464. * // ]
  465. * ```
  466. *
  467. * @param array $array
  468. * @param string|\Closure $from
  469. * @param string|\Closure $to
  470. * @param string|\Closure $group
  471. * @return array
  472. */
  473. public static function map($array, $from, $to, $group = null)
  474. {
  475. $result = [];
  476. foreach ($array as $element) {
  477. $key = static::getValue($element, $from);
  478. $value = static::getValue($element, $to);
  479. if ($group !== null) {
  480. $result[static::getValue($element, $group)][$key] = $value;
  481. } else {
  482. $result[$key] = $value;
  483. }
  484. }
  485. return $result;
  486. }
  487. /**
  488. * Checks if the given array contains the specified key.
  489. * This method enhances the `array_key_exists()` function by supporting case-insensitive
  490. * key comparison.
  491. * @param string $key the key to check
  492. * @param array $array the array with keys to check
  493. * @param bool $caseSensitive whether the key comparison should be case-sensitive
  494. * @return bool whether the array contains the specified key
  495. */
  496. public static function keyExists($key, $array, $caseSensitive = true)
  497. {
  498. if ($caseSensitive) {
  499. // Function `isset` checks key faster but skips `null`, `array_key_exists` handles this case
  500. // http://php.net/manual/en/function.array-key-exists.php#107786
  501. return isset($array[$key]) || array_key_exists($key, $array);
  502. } else {
  503. foreach (array_keys($array) as $k) {
  504. if (strcasecmp($key, $k) === 0) {
  505. return true;
  506. }
  507. }
  508. return false;
  509. }
  510. }
  511. /**
  512. * Sorts an array of objects or arrays (with the same structure) by one or several keys.
  513. * @param array $array the array to be sorted. The array will be modified after calling this method.
  514. * @param string|\Closure|array $key the key(s) to be sorted by. This refers to a key name of the sub-array
  515. * elements, a property name of the objects, or an anonymous function returning the values for comparison
  516. * purpose. The anonymous function signature should be: `function($item)`.
  517. * To sort by multiple keys, provide an array of keys here.
  518. * @param int|array $direction the sorting direction. It can be either `SORT_ASC` or `SORT_DESC`.
  519. * When sorting by multiple keys with different sorting directions, use an array of sorting directions.
  520. * @param int|array $sortFlag the PHP sort flag. Valid values include
  521. * `SORT_REGULAR`, `SORT_NUMERIC`, `SORT_STRING`, `SORT_LOCALE_STRING`, `SORT_NATURAL` and `SORT_FLAG_CASE`.
  522. * Please refer to [PHP manual](http://php.net/manual/en/function.sort.php)
  523. * for more details. When sorting by multiple keys with different sort flags, use an array of sort flags.
  524. * @throws InvalidParamException if the $direction or $sortFlag parameters do not have
  525. * correct number of elements as that of $key.
  526. */
  527. public static function multisort(&$array, $key, $direction = SORT_ASC, $sortFlag = SORT_REGULAR)
  528. {
  529. $keys = is_array($key) ? $key : [$key];
  530. if (empty($keys) || empty($array)) {
  531. return;
  532. }
  533. $n = count($keys);
  534. if (is_scalar($direction)) {
  535. $direction = array_fill(0, $n, $direction);
  536. } elseif (count($direction) !== $n) {
  537. throw new InvalidParamException('The length of $direction parameter must be the same as that of $keys.');
  538. }
  539. if (is_scalar($sortFlag)) {
  540. $sortFlag = array_fill(0, $n, $sortFlag);
  541. } elseif (count($sortFlag) !== $n) {
  542. throw new InvalidParamException('The length of $sortFlag parameter must be the same as that of $keys.');
  543. }
  544. $args = [];
  545. foreach ($keys as $i => $key) {
  546. $flag = $sortFlag[$i];
  547. $args[] = static::getColumn($array, $key);
  548. $args[] = $direction[$i];
  549. $args[] = $flag;
  550. }
  551. // This fix is used for cases when main sorting specified by columns has equal values
  552. // Without it it will lead to Fatal Error: Nesting level too deep - recursive dependency?
  553. $args[] = range(1, count($array));
  554. $args[] = SORT_ASC;
  555. $args[] = SORT_NUMERIC;
  556. $args[] = &$array;
  557. call_user_func_array('array_multisort', $args);
  558. }
  559. /**
  560. * Encodes special characters in an array of strings into HTML entities.
  561. * Only array values will be encoded by default.
  562. * If a value is an array, this method will also encode it recursively.
  563. * Only string values will be encoded.
  564. * @param array $data data to be encoded
  565. * @param bool $valuesOnly whether to encode array values only. If false,
  566. * both the array keys and array values will be encoded.
  567. * @param string $charset the charset that the data is using. If not set,
  568. * [[\yii\base\Application::charset]] will be used.
  569. * @return array the encoded data
  570. * @see http://www.php.net/manual/en/function.htmlspecialchars.php
  571. */
  572. public static function htmlEncode($data, $valuesOnly = true, $charset = null)
  573. {
  574. if ($charset === null) {
  575. $charset = Yii::$app ? Yii::$app->charset : 'UTF-8';
  576. }
  577. $d = [];
  578. foreach ($data as $key => $value) {
  579. if (!$valuesOnly && is_string($key)) {
  580. $key = htmlspecialchars($key, ENT_QUOTES | ENT_SUBSTITUTE, $charset);
  581. }
  582. if (is_string($value)) {
  583. $d[$key] = htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, $charset);
  584. } elseif (is_array($value)) {
  585. $d[$key] = static::htmlEncode($value, $valuesOnly, $charset);
  586. } else {
  587. $d[$key] = $value;
  588. }
  589. }
  590. return $d;
  591. }
  592. /**
  593. * Decodes HTML entities into the corresponding characters in an array of strings.
  594. * Only array values will be decoded by default.
  595. * If a value is an array, this method will also decode it recursively.
  596. * Only string values will be decoded.
  597. * @param array $data data to be decoded
  598. * @param bool $valuesOnly whether to decode array values only. If false,
  599. * both the array keys and array values will be decoded.
  600. * @return array the decoded data
  601. * @see http://www.php.net/manual/en/function.htmlspecialchars-decode.php
  602. */
  603. public static function htmlDecode($data, $valuesOnly = true)
  604. {
  605. $d = [];
  606. foreach ($data as $key => $value) {
  607. if (!$valuesOnly && is_string($key)) {
  608. $key = htmlspecialchars_decode($key, ENT_QUOTES);
  609. }
  610. if (is_string($value)) {
  611. $d[$key] = htmlspecialchars_decode($value, ENT_QUOTES);
  612. } elseif (is_array($value)) {
  613. $d[$key] = static::htmlDecode($value);
  614. } else {
  615. $d[$key] = $value;
  616. }
  617. }
  618. return $d;
  619. }
  620. /**
  621. * Returns a value indicating whether the given array is an associative array.
  622. *
  623. * An array is associative if all its keys are strings. If `$allStrings` is false,
  624. * then an array will be treated as associative if at least one of its keys is a string.
  625. *
  626. * Note that an empty array will NOT be considered associative.
  627. *
  628. * @param array $array the array being checked
  629. * @param bool $allStrings whether the array keys must be all strings in order for
  630. * the array to be treated as associative.
  631. * @return bool whether the array is associative
  632. */
  633. public static function isAssociative($array, $allStrings = true)
  634. {
  635. if (!is_array($array) || empty($array)) {
  636. return false;
  637. }
  638. if ($allStrings) {
  639. foreach ($array as $key => $value) {
  640. if (!is_string($key)) {
  641. return false;
  642. }
  643. }
  644. return true;
  645. } else {
  646. foreach ($array as $key => $value) {
  647. if (is_string($key)) {
  648. return true;
  649. }
  650. }
  651. return false;
  652. }
  653. }
  654. /**
  655. * Returns a value indicating whether the given array is an indexed array.
  656. *
  657. * An array is indexed if all its keys are integers. If `$consecutive` is true,
  658. * then the array keys must be a consecutive sequence starting from 0.
  659. *
  660. * Note that an empty array will be considered indexed.
  661. *
  662. * @param array $array the array being checked
  663. * @param bool $consecutive whether the array keys must be a consecutive sequence
  664. * in order for the array to be treated as indexed.
  665. * @return bool whether the array is associative
  666. */
  667. public static function isIndexed($array, $consecutive = false)
  668. {
  669. if (!is_array($array)) {
  670. return false;
  671. }
  672. if (empty($array)) {
  673. return true;
  674. }
  675. if ($consecutive) {
  676. return array_keys($array) === range(0, count($array) - 1);
  677. } else {
  678. foreach ($array as $key => $value) {
  679. if (!is_int($key)) {
  680. return false;
  681. }
  682. }
  683. return true;
  684. }
  685. }
  686. /**
  687. * Check whether an array or [[\Traversable]] contains an element.
  688. *
  689. * This method does the same as the PHP function [in_array()](http://php.net/manual/en/function.in-array.php)
  690. * but additionally works for objects that implement the [[\Traversable]] interface.
  691. * @param mixed $needle The value to look for.
  692. * @param array|\Traversable $haystack The set of values to search.
  693. * @param bool $strict Whether to enable strict (`===`) comparison.
  694. * @return bool `true` if `$needle` was found in `$haystack`, `false` otherwise.
  695. * @throws InvalidParamException if `$haystack` is neither traversable nor an array.
  696. * @see http://php.net/manual/en/function.in-array.php
  697. * @since 2.0.7
  698. */
  699. public static function isIn($needle, $haystack, $strict = false)
  700. {
  701. if ($haystack instanceof \Traversable) {
  702. foreach ($haystack as $value) {
  703. if ($needle == $value && (!$strict || $needle === $value)) {
  704. return true;
  705. }
  706. }
  707. } elseif (is_array($haystack)) {
  708. return in_array($needle, $haystack, $strict);
  709. } else {
  710. throw new InvalidParamException('Argument $haystack must be an array or implement Traversable');
  711. }
  712. return false;
  713. }
  714. /**
  715. * Checks whether a variable is an array or [[\Traversable]].
  716. *
  717. * This method does the same as the PHP function [is_array()](http://php.net/manual/en/function.is-array.php)
  718. * but additionally works on objects that implement the [[\Traversable]] interface.
  719. * @param mixed $var The variable being evaluated.
  720. * @return bool whether $var is array-like
  721. * @see http://php.net/manual/en/function.is_array.php
  722. * @since 2.0.8
  723. */
  724. public static function isTraversable($var)
  725. {
  726. return is_array($var) || $var instanceof \Traversable;
  727. }
  728. /**
  729. * Checks whether an array or [[\Traversable]] is a subset of another array or [[\Traversable]].
  730. *
  731. * This method will return `true`, if all elements of `$needles` are contained in
  732. * `$haystack`. If at least one element is missing, `false` will be returned.
  733. * @param array|\Traversable $needles The values that must **all** be in `$haystack`.
  734. * @param array|\Traversable $haystack The set of value to search.
  735. * @param bool $strict Whether to enable strict (`===`) comparison.
  736. * @throws InvalidParamException if `$haystack` or `$needles` is neither traversable nor an array.
  737. * @return bool `true` if `$needles` is a subset of `$haystack`, `false` otherwise.
  738. * @since 2.0.7
  739. */
  740. public static function isSubset($needles, $haystack, $strict = false)
  741. {
  742. if (is_array($needles) || $needles instanceof \Traversable) {
  743. foreach ($needles as $needle) {
  744. if (!static::isIn($needle, $haystack, $strict)) {
  745. return false;
  746. }
  747. }
  748. return true;
  749. } else {
  750. throw new InvalidParamException('Argument $needles must be an array or implement Traversable');
  751. }
  752. }
  753. /**
  754. * Filters array according to rules specified.
  755. *
  756. * For example:
  757. *
  758. * ```php
  759. * $array = [
  760. * 'A' => [1, 2],
  761. * 'B' => [
  762. * 'C' => 1,
  763. * 'D' => 2,
  764. * ],
  765. * 'E' => 1,
  766. * ];
  767. *
  768. * $result = \yii\helpers\ArrayHelper::filter($array, ['A']);
  769. * // $result will be:
  770. * // [
  771. * // 'A' => [1, 2],
  772. * // ]
  773. *
  774. * $result = \yii\helpers\ArrayHelper::filter($array, ['A', 'B.C']);
  775. * // $result will be:
  776. * // [
  777. * // 'A' => [1, 2],
  778. * // 'B' => ['C' => 1],
  779. * // ]
  780. *
  781. * $result = \yii\helpers\ArrayHelper::filter($array, ['B', '!B.C']);
  782. * // $result will be:
  783. * // [
  784. * // 'B' => ['D' => 2],
  785. * // ]
  786. * ```
  787. *
  788. * @param array $array Source array
  789. * @param array $filters Rules that define array keys which should be left or removed from results.
  790. * Each rule is:
  791. * - `var` - `$array['var']` will be left in result.
  792. * - `var.key` = only `$array['var']['key'] will be left in result.
  793. * - `!var.key` = `$array['var']['key'] will be removed from result.
  794. * @return array Filtered array
  795. * @since 2.0.9
  796. */
  797. public static function filter($array, $filters)
  798. {
  799. $result = [];
  800. $forbiddenVars = [];
  801. foreach ($filters as $var) {
  802. $keys = explode('.', $var);
  803. $globalKey = $keys[0];
  804. $localKey = isset($keys[1]) ? $keys[1] : null;
  805. if ($globalKey[0] === '!') {
  806. $forbiddenVars[] = [
  807. substr($globalKey, 1),
  808. $localKey,
  809. ];
  810. continue;
  811. }
  812. if (empty($array[$globalKey])) {
  813. continue;
  814. }
  815. if ($localKey === null) {
  816. $result[$globalKey] = $array[$globalKey];
  817. continue;
  818. }
  819. if (!isset($array[$globalKey][$localKey])) {
  820. continue;
  821. }
  822. if (!array_key_exists($globalKey, $result)) {
  823. $result[$globalKey] = [];
  824. }
  825. $result[$globalKey][$localKey] = $array[$globalKey][$localKey];
  826. }
  827. foreach ($forbiddenVars as $var) {
  828. list($globalKey, $localKey) = $var;
  829. if (array_key_exists($globalKey, $result)) {
  830. unset($result[$globalKey][$localKey]);
  831. }
  832. }
  833. return $result;
  834. }
  835. }