BaseArrayHelper.php 34 KB

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