BaseArrayHelper.php 34 KB

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