BaseArrayHelper.php 15.4 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7
<?php
/**
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @link http://www.yiiframework.com/
 * @license http://www.yiiframework.com/license/
 */

8
namespace yii\helpers;
Qiang Xue committed
9 10

use Yii;
11
use yii\base\Arrayable;
Qiang Xue committed
12 13 14
use yii\base\InvalidParamException;

/**
15
 * BaseArrayHelper provides concrete implementation for [[ArrayHelper]].
16
 *
17
 * Do not use BaseArrayHelper. Use [[ArrayHelper]] instead.
Qiang Xue committed
18 19 20 21
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
22
class BaseArrayHelper
Qiang Xue committed
23
{
24
	/**
25
	 * Converts an object or an array of objects into an array.
26
	 * @param object|array $object the object to be converted into an array
27 28 29 30
	 * @param array $properties a mapping from object class names to the properties that need to put into the resulting arrays.
	 * The properties specified for each class is an array of the following format:
	 *
	 * ~~~
Alexander Makarov committed
31 32
	 * [
	 *     'app\models\Post' => [
33 34 35
	 *         'id',
	 *         'title',
	 *         // the key name in array result => property name
36
	 *         'createTime' => 'created_at',
37 38 39 40
	 *         // the key name in array result => anonymous function
	 *         'length' => function ($post) {
	 *             return strlen($post->content);
	 *         },
Alexander Makarov committed
41 42
	 *     ],
	 * ]
43 44 45 46 47
	 * ~~~
	 *
	 * The result of `ArrayHelper::toArray($post, $properties)` could be like the following:
	 *
	 * ~~~
Alexander Makarov committed
48
	 * [
49 50 51 52
	 *     'id' => 123,
	 *     'title' => 'test',
	 *     'createTime' => '2013-01-01 12:00AM',
	 *     'length' => 301,
Alexander Makarov committed
53
	 * ]
54 55
	 * ~~~
	 *
56 57 58
	 * @param boolean $recursive whether to recursively converts properties which are objects into arrays.
	 * @return array the array representation of the object
	 */
Alexander Makarov committed
59
	public static function toArray($object, $properties = [], $recursive = true)
60
	{
61 62 63
		if (!empty($properties) && is_object($object)) {
			$className = get_class($object);
			if (!empty($properties[$className])) {
Alexander Makarov committed
64
				$result = [];
65 66 67 68 69 70 71 72 73 74
				foreach ($properties[$className] as $key => $name) {
					if (is_int($key)) {
						$result[$name] = $object->$name;
					} else {
						$result[$key] = static::getValue($object, $name);
					}
				}
				return $result;
			}
		}
75 76 77 78 79 80
		if ($object instanceof Arrayable) {
			$object = $object->toArray();
			if (!$recursive) {
				return $object;
			}
		}
Alexander Makarov committed
81
		$result = [];
82 83 84 85 86 87 88 89 90 91
		foreach ($object as $key => $value) {
			if ($recursive && (is_array($value) || is_object($value))) {
				$result[$key] = static::toArray($value, true);
			} else {
				$result[$key] = $value;
			}
		}
		return $result;
	}

Qiang Xue committed
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
	/**
	 * Merges two or more arrays into one recursively.
	 * If each array has an element with the same string key value, the latter
	 * will overwrite the former (different from array_merge_recursive).
	 * Recursive merging will be conducted if both arrays have an element of array
	 * type and are having the same key.
	 * For integer-keyed elements, the elements from the latter array will
	 * be appended to the former array.
	 * @param array $a array to be merged to
	 * @param array $b array to be merged from. You can specify additional
	 * arrays via third argument, fourth argument etc.
	 * @return array the merged array (the original arrays are not changed.)
	 */
	public static function merge($a, $b)
	{
		$args = func_get_args();
		$res = array_shift($args);
109
		while (!empty($args)) {
Qiang Xue committed
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
			$next = array_shift($args);
			foreach ($next as $k => $v) {
				if (is_integer($k)) {
					isset($res[$k]) ? $res[] = $v : $res[$k] = $v;
				} elseif (is_array($v) && isset($res[$k]) && is_array($res[$k])) {
					$res[$k] = self::merge($res[$k], $v);
				} else {
					$res[$k] = $v;
				}
			}
		}
		return $res;
	}

	/**
	 * Retrieves the value of an array element or object property with the given key or property name.
126 127 128 129 130 131 132 133
	 * If the key does not exist in the array or object, the default value will be returned instead.
	 *
	 * The key may be specified in a dot format to retrieve the value of a sub-array or the property
	 * of an embedded object. In particular, if the key is `x.y.z`, then the returned value would
	 * be `$array['x']['y']['z']` or `$array->x->y->z` (if `$array` is an object). If `$array['x']`
	 * or `$array->x` is neither an array nor an object, the default value will be returned.
	 * Note that if the array already has an element `x.y.z`, then its value will be returned
	 * instead of going through the sub-arrays.
Qiang Xue committed
134 135 136 137 138 139 140 141 142 143 144 145
	 *
	 * Below are some usage examples,
	 *
	 * ~~~
	 * // working with array
	 * $username = \yii\helpers\ArrayHelper::getValue($_POST, 'username');
	 * // working with object
	 * $username = \yii\helpers\ArrayHelper::getValue($user, 'username');
	 * // working with anonymous function
	 * $fullName = \yii\helpers\ArrayHelper::getValue($user, function($user, $defaultValue) {
	 *     return $user->firstName . ' ' . $user->lastName;
	 * });
146 147
	 * // using dot format to retrieve the property of embedded object
	 * $street = \yii\helpers\ArrayHelper::getValue($users, 'address.street');
Qiang Xue committed
148 149 150 151 152 153 154
	 * ~~~
	 *
	 * @param array|object $array array or object to extract value from
	 * @param string|\Closure $key key name of the array element, or property name of the object,
	 * or an anonymous function returning the value. The anonymous function signature should be:
	 * `function($array, $defaultValue)`.
	 * @param mixed $default the default value to be returned if the specified key does not exist
155
	 * @return mixed the value of the element if found, default value otherwise
156
	 * @throws InvalidParamException if $array is neither an array nor an object.
Qiang Xue committed
157 158 159 160 161
	 */
	public static function getValue($array, $key, $default = null)
	{
		if ($key instanceof \Closure) {
			return $key($array, $default);
162 163 164 165 166 167 168 169 170 171 172 173 174
		}

		if (is_array($array) && array_key_exists($key, $array)) {
			return $array[$key];
		}

		if (($pos = strrpos($key, '.')) !== false) {
			$array = static::getValue($array, substr($key, 0, $pos), $default);
			$key = substr($key, $pos + 1);
		}

		if (is_object($array)) {
			return $array->$key;
Qiang Xue committed
175
		} elseif (is_array($array)) {
176
			return array_key_exists($key, $array) ? $array[$key] : $default;
Qiang Xue committed
177
		} else {
178
			return $default;
Qiang Xue committed
179 180 181
		}
	}

182 183 184 185 186 187 188
	/**
	 * Removes an item from an array and returns the value. If the key does not exist in the array, the default value
	 * will be returned instead.
	 *
	 * Usage examples,
	 *
	 * ~~~
Alexander Makarov committed
189
	 * // $array = ['type' => 'A', 'options' => [1, 2]];
190
	 * // working with array
191
	 * $type = \yii\helpers\ArrayHelper::remove($array, 'type');
192
	 * // $array content
Alexander Makarov committed
193
	 * // $array = ['options' => [1, 2]];
194 195 196 197 198 199 200
	 * ~~~
	 *
	 * @param array $array the array to extract value from
	 * @param string $key key name of the array element
	 * @param mixed $default the default value to be returned if the specified key does not exist
	 * @return mixed|null the value of the element if found, default value otherwise
	 */
201
	public static function remove(&$array, $key, $default = null)
202
	{
203 204
		if (is_array($array) && (isset($array[$key]) || array_key_exists($key, $array))) {
			$value = $array[$key];
205 206 207 208 209 210
			unset($array[$key]);
			return $value;
		}
		return $default;
	}

Qiang Xue committed
211 212 213 214 215 216 217 218 219 220 221 222
	/**
	 * Indexes an array according to a specified key.
	 * The input array should be multidimensional or an array of objects.
	 *
	 * The key can be a key name of the sub-array, a property name of object, or an anonymous
	 * function which returns the key value given an array element.
	 *
	 * If a key value is null, the corresponding array element will be discarded and not put in the result.
	 *
	 * For example,
	 *
	 * ~~~
Alexander Makarov committed
223 224 225 226
	 * $array = [
	 *     ['id' => '123', 'data' => 'abc'],
	 *     ['id' => '345', 'data' => 'def'],
	 * ];
Qiang Xue committed
227 228
	 * $result = ArrayHelper::index($array, 'id');
	 * // the result is:
Alexander Makarov committed
229 230 231 232
	 * // [
	 * //     '123' => ['id' => '123', 'data' => 'abc'],
	 * //     '345' => ['id' => '345', 'data' => 'def'],
	 * // ]
Qiang Xue committed
233 234
	 *
	 * // using anonymous function
235
	 * $result = ArrayHelper::index($array, function ($element) {
Qiang Xue committed
236 237 238 239 240 241 242 243 244 245
	 *     return $element['id'];
	 * });
	 * ~~~
	 *
	 * @param array $array the array that needs to be indexed
	 * @param string|\Closure $key the column name or anonymous function whose result will be used to index the array
	 * @return array the indexed array
	 */
	public static function index($array, $key)
	{
Alexander Makarov committed
246
		$result = [];
Qiang Xue committed
247 248 249 250 251 252 253 254 255 256 257 258 259 260
		foreach ($array as $element) {
			$value = static::getValue($element, $key);
			$result[$value] = $element;
		}
		return $result;
	}

	/**
	 * Returns the values of a specified column in an array.
	 * The input array should be multidimensional or an array of objects.
	 *
	 * For example,
	 *
	 * ~~~
Alexander Makarov committed
261 262 263 264
	 * $array = [
	 *     ['id' => '123', 'data' => 'abc'],
	 *     ['id' => '345', 'data' => 'def'],
	 * ];
Qiang Xue committed
265
	 * $result = ArrayHelper::getColumn($array, 'id');
Alexander Makarov committed
266
	 * // the result is: ['123', '345']
Qiang Xue committed
267 268
	 *
	 * // using anonymous function
269
	 * $result = ArrayHelper::getColumn($array, function ($element) {
Qiang Xue committed
270 271 272 273 274 275 276 277 278 279 280 281
	 *     return $element['id'];
	 * });
	 * ~~~
	 *
	 * @param array $array
	 * @param string|\Closure $name
	 * @param boolean $keepKeys whether to maintain the array keys. If false, the resulting array
	 * will be re-indexed with integers.
	 * @return array the list of column values
	 */
	public static function getColumn($array, $name, $keepKeys = true)
	{
Alexander Makarov committed
282
		$result = [];
Qiang Xue committed
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
		if ($keepKeys) {
			foreach ($array as $k => $element) {
				$result[$k] = static::getValue($element, $name);
			}
		} else {
			foreach ($array as $element) {
				$result[] = static::getValue($element, $name);
			}
		}

		return $result;
	}

	/**
	 * Builds a map (key-value pairs) from a multidimensional array or an array of objects.
	 * The `$from` and `$to` parameters specify the key names or property names to set up the map.
	 * Optionally, one can further group the map according to a grouping field `$group`.
	 *
	 * For example,
	 *
	 * ~~~
Alexander Makarov committed
304 305 306 307
	 * $array = [
	 *     ['id' => '123', 'name' => 'aaa', 'class' => 'x'],
	 *     ['id' => '124', 'name' => 'bbb', 'class' => 'x'],
	 *     ['id' => '345', 'name' => 'ccc', 'class' => 'y'],
Qiang Xue committed
308 309 310 311
	 * );
	 *
	 * $result = ArrayHelper::map($array, 'id', 'name');
	 * // the result is:
Alexander Makarov committed
312
	 * // [
Qiang Xue committed
313 314 315
	 * //     '123' => 'aaa',
	 * //     '124' => 'bbb',
	 * //     '345' => 'ccc',
Alexander Makarov committed
316
	 * // ]
Qiang Xue committed
317 318 319
	 *
	 * $result = ArrayHelper::map($array, 'id', 'name', 'class');
	 * // the result is:
Alexander Makarov committed
320 321
	 * // [
	 * //     'x' => [
Qiang Xue committed
322 323
	 * //         '123' => 'aaa',
	 * //         '124' => 'bbb',
Alexander Makarov committed
324 325
	 * //     ],
	 * //     'y' => [
Qiang Xue committed
326
	 * //         '345' => 'ccc',
Alexander Makarov committed
327 328
	 * //     ],
	 * // ]
Qiang Xue committed
329 330 331 332 333 334 335 336 337 338
	 * ~~~
	 *
	 * @param array $array
	 * @param string|\Closure $from
	 * @param string|\Closure $to
	 * @param string|\Closure $group
	 * @return array
	 */
	public static function map($array, $from, $to, $group = null)
	{
Alexander Makarov committed
339
		$result = [];
Qiang Xue committed
340 341 342 343 344 345 346 347 348 349 350 351
		foreach ($array as $element) {
			$key = static::getValue($element, $from);
			$value = static::getValue($element, $to);
			if ($group !== null) {
				$result[static::getValue($element, $group)][$key] = $value;
			} else {
				$result[$key] = $value;
			}
		}
		return $result;
	}

352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
	/**
	 * Checks if the given array contains the specified key.
	 * This method enhances the `array_key_exists()` function by supporting case-insensitive
	 * key comparison.
	 * @param string $key the key to check
	 * @param array $array the array with keys to check
	 * @param boolean $caseSensitive whether the key comparison should be case-sensitive
	 * @return boolean whether the array contains the specified key
	 */
	public static function keyExists($key, $array, $caseSensitive = true)
	{
		if ($caseSensitive) {
			return array_key_exists($key, $array);
		} else {
			foreach (array_keys($array) as $k) {
				if (strcasecmp($key, $k) === 0) {
					return true;
				}
			}
			return false;
		}
	}

Qiang Xue committed
375 376 377 378 379 380 381
	/**
	 * Sorts an array of objects or arrays (with the same structure) by one or several keys.
	 * @param array $array the array to be sorted. The array will be modified after calling this method.
	 * @param string|\Closure|array $key the key(s) to be sorted by. This refers to a key name of the sub-array
	 * elements, a property name of the objects, or an anonymous function returning the values for comparison
	 * purpose. The anonymous function signature should be: `function($item)`.
	 * To sort by multiple keys, provide an array of keys here.
Qiang Xue committed
382 383
	 * @param integer|array $direction the sorting direction. It can be either `SORT_ASC` or `SORT_DESC`.
	 * When sorting by multiple keys with different sorting directions, use an array of sorting directions.
384
	 * @param integer|array $sortFlag the PHP sort flag. Valid values include
385
	 * `SORT_REGULAR`, `SORT_NUMERIC`, `SORT_STRING`, `SORT_LOCALE_STRING`, `SORT_NATURAL` and `SORT_FLAG_CASE`.
386
	 * Please refer to [PHP manual](http://php.net/manual/en/function.sort.php)
387
	 * for more details. When sorting by multiple keys with different sort flags, use an array of sort flags.
slavcopost committed
388
	 * @throws InvalidParamException if the $descending or $sortFlag parameters do not have
Qiang Xue committed
389 390
	 * correct number of elements as that of $key.
	 */
391
	public static function multisort(&$array, $key, $direction = SORT_ASC, $sortFlag = SORT_REGULAR)
Qiang Xue committed
392
	{
Alexander Makarov committed
393
		$keys = is_array($key) ? $key : [$key];
Qiang Xue committed
394 395 396 397
		if (empty($keys) || empty($array)) {
			return;
		}
		$n = count($keys);
Qiang Xue committed
398 399 400
		if (is_scalar($direction)) {
			$direction = array_fill(0, $n, $direction);
		} elseif (count($direction) !== $n) {
slavcopost committed
401
			throw new InvalidParamException('The length of $descending parameter must be the same as that of $keys.');
Qiang Xue committed
402 403 404 405
		}
		if (is_scalar($sortFlag)) {
			$sortFlag = array_fill(0, $n, $sortFlag);
		} elseif (count($sortFlag) !== $n) {
406 407
			throw new InvalidParamException('The length of $sortFlag parameter must be the same as that of $keys.');
		}
Alexander Makarov committed
408
		$args = [];
Qiang Xue committed
409 410
		foreach ($keys as $i => $key) {
			$flag = $sortFlag[$i];
411
			$args[] = static::getColumn($array, $key);
Qiang Xue committed
412
			$args[] = $direction[$i];
Qiang Xue committed
413 414
			$args[] = $flag;
		}
415
		$args[] = &$array;
Qiang Xue committed
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
		call_user_func_array('array_multisort', $args);
	}

	/**
	 * Encodes special characters in an array of strings into HTML entities.
	 * Both the array keys and values will be encoded.
	 * If a value is an array, this method will also encode it recursively.
	 * @param array $data data to be encoded
	 * @param boolean $valuesOnly whether to encode array values only. If false,
	 * both the array keys and array values will be encoded.
	 * @param string $charset the charset that the data is using. If not set,
	 * [[\yii\base\Application::charset]] will be used.
	 * @return array the encoded data
	 * @see http://www.php.net/manual/en/function.htmlspecialchars.php
	 */
	public static function htmlEncode($data, $valuesOnly = true, $charset = null)
	{
		if ($charset === null) {
			$charset = Yii::$app->charset;
		}
Alexander Makarov committed
436
		$d = [];
Qiang Xue committed
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
		foreach ($data as $key => $value) {
			if (!$valuesOnly && is_string($key)) {
				$key = htmlspecialchars($key, ENT_QUOTES, $charset);
			}
			if (is_string($value)) {
				$d[$key] = htmlspecialchars($value, ENT_QUOTES, $charset);
			} elseif (is_array($value)) {
				$d[$key] = static::htmlEncode($value, $charset);
			}
		}
		return $d;
	}

	/**
	 * Decodes HTML entities into the corresponding characters in an array of strings.
	 * Both the array keys and values will be decoded.
	 * If a value is an array, this method will also decode it recursively.
	 * @param array $data data to be decoded
	 * @param boolean $valuesOnly whether to decode array values only. If false,
	 * both the array keys and array values will be decoded.
	 * @return array the decoded data
	 * @see http://www.php.net/manual/en/function.htmlspecialchars-decode.php
	 */
	public static function htmlDecode($data, $valuesOnly = true)
	{
Alexander Makarov committed
462
		$d = [];
Qiang Xue committed
463 464 465 466 467 468 469 470 471 472 473 474
		foreach ($data as $key => $value) {
			if (!$valuesOnly && is_string($key)) {
				$key = htmlspecialchars_decode($key, ENT_QUOTES);
			}
			if (is_string($value)) {
				$d[$key] = htmlspecialchars_decode($value, ENT_QUOTES);
			} elseif (is_array($value)) {
				$d[$key] = static::htmlDecode($value);
			}
		}
		return $d;
	}
Zander Baldwin committed
475
}