ArrayHelper::get()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 12
rs 9.2
nc 4
cc 4
eloc 9
nop 3
1
<?php
2
/*
3
 * This file is part of Yolk - Gamer Network's PHP Framework.
4
 *
5
 * Copyright (c) 2013 Gamer Network Ltd.
6
 * 
7
 * Distributed under the MIT License, a copy of which is available in the
8
 * LICENSE file that was bundled with this package, or online at:
9
 * https://github.com/gamernetwork/yolk-core
10
 */
11
12
namespace yolk\helpers;
13
14
class ArrayHelper {
15
16
	/**
17
	 * Helpers cannot be instantiated.
18
	 */
19
	private function __construct() {}
20
21
	/**
22
	 * Convert a variable into an array of unique integer values.
23
	 *
24
	 * @param  mixed   $var
25
	 * @return array
26
	 */
27
	public static function uniqueIntegers( $var ) {
28
		return array_unique(
29
			array_map(
30
				'intval',
31
				(array) $var
32
			)
33
		);
34
	}
35
36
	/**
37
	 * Determines if a variable can be iterated via foreach.
38
	 * @param  mixed  $var
39
	 * @return boolean
40
	 */
41
	public static function isTraversable( $var ) {
42
		return is_array($var) || ($var instanceof \Traversable);
43
	}
44
45
	/**
46
	 * Determine if an array is an associative array.
47
	 * Taken from: http://stackoverflow.com/questions/173400/php-arrays-a-good-way-to-check-if-an-array-is-associative-or-numeric/4254008#4254008
48
	 *
49
	 * @param  array   $var
50
	 * @return bool
51
	 */
52
	public static function isAssoc( $var ) {
53
		return (bool) count(
54
			array_filter(
55
				array_keys($var),
56
				'is_string'
57
			)
58
		);
59
	}
60
61
	/**
62
	 * Filter an array and return all entries that are instances of the specified class.
63
	 *
64
	 * @param  array   $var     An array to filter
65
	 * @param  string  $class   The class that items should be an instance of
66
	 * @return array
67
	 */
68
	public static function filterObjects( $var, $class ) {
69
		if( !is_array($var) )
70
			$var = array($var);
71
		return array_filter(
72
			$var,
73
			function( $item ) use ($class) {
74
				return ($item instanceof $class);
75
			}
76
		);
77
	}
78
79
	/**
80
	 * Return value of the specified key from an array or object or a default if the key isn't set.
81
	 * @param  array|object   $var
82
	 * @param  string|integer $key
83
	 * @param  mixed          $default
84
	 * @return mixed
85
	 */
86
	public static function get( $var, $key, $default = null ) {
87
88
		if( $key === null )
89
			return $var;
90
		elseif( isset($var->$key) )
91
			return $var->$key;
92
		elseif( isset($var[$key]) )
93
			return $var[$key];
94
		else
95
			return $default;
96
97
	}
98
99
	/**
100
	 * Extract the items that are null from an array; keys are preserved.
101
	 * @param  array $var
102
	 * @return array
103
	 */
104
	public static function getNullItems( $var ) {
105
		return array_filter($var, function( $a ) { return $a === null; });
106
	}
107
108
	/**
109
	 * Extract a single field from an array of arrays or objects.
110
	 *
111
	 * @param  array   $vars            An array or arrays or objects
112
	 * @param  string  $field           The field to get values from
113
	 * @param  boolean $preserve_keys   Whether or not to preserve the array keys
114
	 * @return array
115
	 */
116
	public static function pluck( $vars, $field, $preserve_keys = true ) {
117
		$values = [];
118
		foreach( $vars as $k => $v ) {
119
			$values[$k] = static::get($v, $field);
120
		}
121
		return $preserve_keys ? $values : array_values($values);
122
	}
123
124
	/**
125
	 * Sum a single field from an array of arrays or objects.
126
	 *
127
	 * @param  array   $vars    An array
128
	 * @param  string  $field   The field to get values from
129
	 * @return array
130
	 */
131
	public static function sum( $vars, $field ) {
132
		return array_sum(static::pluck($vars, $field));
133
	}
134
135
	/**
136
	 * Return the minimum value of a single field from an array of arrays or objects.
137
	 *
138
	 * @param  array   $vars    An array
139
	 * @param  string  $field   The field to get values from
140
	 * @return array
141
	 */
142
	public static function min( $vars, $field ) {
143
		return min(static::pluck($vars, $field));
144
	}
145
146
	/**
147
	 * Return the maximum value of a single field from an array of arrays or objects.
148
	 *
149
	 * @param  array   $vars    An array
150
	 * @param  string  $field   The field to get values from
151
	 * @return array
152
	 */
153
	public static function max( $vars, $field ) {
154
		return max(static::pluck($vars, $field));
155
	}
156
157
	/**
158
	 * Implode an associative array into a string of key/value pairs.
159
	 *
160
	 * @param  array   $var          The array to implode
161
	 * @param  string  $glue_outer   A string used to delimit items
162
	 * @param  string  $glue_inner   A string used to separate keys and values 
163
	 * @param  boolean $skip_empty   Should empty values be included?
164
	 * @return string
165
	 */
166
	public static function implodeAssoc( $var, $glue_outer = ',', $glue_inner = '=', $skip_empty = true ) {
167
		$output = [];
168
		foreach( $var as $k => $v ) {
169
			if( !$skip_empty || !empty($v) ) {
170
				$output[] = "{$k}{$glue_inner}{$v}";
171
			}
172
		}
173
		return implode($glue_outer, $output);
174
	}
175
176
	/**
177
	 * Create a comparison function for sorting multi-dimensional arrays.
178
	 * http://stackoverflow.com/questions/96759/how-do-i-sort-a-multidimensional-array-in-php/16788610#16788610
179
	 *
180
	 * Each parameter to this function is a criteria and can either be a string
181
	 * representing a column to sort or a numerically indexed array containing:
182
	 * 0 => the column name to sort on (mandatory)
183
	 * 1 => either SORT_ASC or SORT_DESC (optional)
184
	 * 2 => a projection function (optional)
185
	 * 
186
	 * The return value is a function that can be passed to usort() or uasort().
187
	 *
188
	 * @return \Closure
189
	 */
190
	public static function makeComparer() {
191
192
		// normalize criteria up front so that the comparer finds everything tidy
193
		$criteria = func_get_args();
194
		foreach( $criteria as $index => $criterion ) {
195
			$criteria[$index] = is_array($criterion)
196
				? array_pad($criterion, 3, null)
197
				: array($criterion, SORT_ASC, null);
198
		}
199
200
		return function( $first, $second ) use ($criteria) {
201
			foreach( $criteria as $criterion ) {
202
203
				// how will we compare this round?
204
				list($column, $sort_order, $projection) = $criterion;
205
				$sort_order = $sort_order === SORT_DESC ? -1 : 1;
206
207
				// if a projection was defined project the values now
208
				if( $projection ) {
209
					$lhs = call_user_func($projection, $first[$column]);
210
					$rhs = call_user_func($projection, $second[$column]);
211
				}
212
				else {
213
					$lhs = $first[$column];
214
					$rhs = $second[$column];
215
				}
216
217
				// do the actual comparison; do not return if equal, move on to the next column
218
				if( $lhs < $rhs ) {
219
					return -1 * $sort_order;
220
				}
221
				else if ($lhs > $rhs) {
222
					return 1 * $sort_order;
223
				}
224
225
			}
226
			return 0; // all sortable columns contain the same values, so $first == $second
227
		};
228
229
	}
230
231
}
232
233
// EOF