PHPExcel_Calculation_LookupRef::MATCH()   F
last analyzed

Complexity

Conditions 29
Paths 218

Size

Total Lines 98
Code Lines 42

Duplication

Lines 7
Ratio 7.14 %

Importance

Changes 0
Metric Value
cc 29
eloc 42
c 0
b 0
f 0
nc 218
nop 3
dl 7
loc 98
rs 3.958

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * PHPExcel
4
 *
5
 * Copyright (c) 2006 - 2012 PHPExcel
6
 *
7
 * This library is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * This library is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with this library; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 *
21
 * @category	PHPExcel
22
 * @package		PHPExcel_Calculation
23
 * @copyright	Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
24
 * @license		http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt	LGPL
25
 * @version		1.7.7, 2012-05-19
26
 */
27
28
29
/** PHPExcel root directory */
30 View Code Duplication
if (!defined('PHPEXCEL_ROOT')) {
31
	/**
32
	 * @ignore
33
	 */
34
	define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
35
	require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
36
}
37
38
39
/**
40
 * PHPExcel_Calculation_LookupRef
41
 *
42
 * @category	PHPExcel
43
 * @package		PHPExcel_Calculation
44
 * @copyright	Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
45
 */
46
class PHPExcel_Calculation_LookupRef {
47
48
49
	/**
50
	 * CELL_ADDRESS
51
	 *
52
	 * Creates a cell address as text, given specified row and column numbers.
53
	 *
54
	 * Excel Function:
55
	 *		=ADDRESS(row, column, [relativity], [referenceStyle], [sheetText])
56
	 *
57
	 * @param	row				Row number to use in the cell reference
58
	 * @param	column			Column number to use in the cell reference
59
	 * @param	relativity		Flag indicating the type of reference to return
60
	 *								1 or omitted	Absolute
61
	 *								2				Absolute row; relative column
62
	 *								3				Relative row; absolute column
63
	 *								4				Relative
64
	 * @param	referenceStyle	A logical value that specifies the A1 or R1C1 reference style.
65
	 *								TRUE or omitted		CELL_ADDRESS returns an A1-style reference
66
	 *								FALSE				CELL_ADDRESS returns an R1C1-style reference
67
	 * @param	sheetText		Optional Name of worksheet to use
68
	 * @return	string
69
	 */
70
	public static function CELL_ADDRESS($row, $column, $relativity=1, $referenceStyle=True, $sheetText='') {
71
		$row		= PHPExcel_Calculation_Functions::flattenSingleValue($row);
72
		$column		= PHPExcel_Calculation_Functions::flattenSingleValue($column);
73
		$relativity	= PHPExcel_Calculation_Functions::flattenSingleValue($relativity);
74
		$sheetText	= PHPExcel_Calculation_Functions::flattenSingleValue($sheetText);
75
76
		if (($row < 1) || ($column < 1)) {
77
			return PHPExcel_Calculation_Functions::VALUE();
78
		}
79
80
		if ($sheetText > '') {
81
			if (strpos($sheetText,' ') !== False) { $sheetText = "'".$sheetText."'"; }
82
			$sheetText .='!';
83
		}
84
		if ((!is_bool($referenceStyle)) || $referenceStyle) {
85
			$rowRelative = $columnRelative = '$';
86
			$column = PHPExcel_Cell::stringFromColumnIndex($column-1);
87
			if (($relativity == 2) || ($relativity == 4)) { $columnRelative = ''; }
88
			if (($relativity == 3) || ($relativity == 4)) { $rowRelative = ''; }
89
			return $sheetText.$columnRelative.$column.$rowRelative.$row;
90
		} else {
91
			if (($relativity == 2) || ($relativity == 4)) { $column = '['.$column.']'; }
92
			if (($relativity == 3) || ($relativity == 4)) { $row = '['.$row.']'; }
93
			return $sheetText.'R'.$row.'C'.$column;
94
		}
95
	}	//	function CELL_ADDRESS()
96
97
98
	/**
99
	 * COLUMN
100
	 *
101
	 * Returns the column number of the given cell reference
102
	 * If the cell reference is a range of cells, COLUMN returns the column numbers of each column in the reference as a horizontal array.
103
	 * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the
104
	 *		reference of the cell in which the COLUMN function appears; otherwise this function returns 0.
105
	 *
106
	 * Excel Function:
107
	 *		=COLUMN([cellAddress])
108
	 *
109
	 * @param	cellAddress		A reference to a range of cells for which you want the column numbers
110
	 * @return	integer or array of integer
111
	 */
112
	public static function COLUMN($cellAddress=Null) {
113
		if (is_null($cellAddress) || trim($cellAddress) === '') { return 0; }
114
115
		if (is_array($cellAddress)) {
116
			foreach($cellAddress as $columnKey => $value) {
117
				$columnKey = preg_replace('/[^a-z]/i','',$columnKey);
118
				return (integer) PHPExcel_Cell::columnIndexFromString($columnKey);
119
			}
120 View Code Duplication
		} else {
121
			if (strpos($cellAddress,'!') !== false) {
122
				list($sheet,$cellAddress) = explode('!',$cellAddress);
0 ignored issues
show
Unused Code introduced by
The assignment to $sheet is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
123
			}
124
			if (strpos($cellAddress,':') !== false) {
125
				list($startAddress,$endAddress) = explode(':',$cellAddress);
126
				$startAddress = preg_replace('/[^a-z]/i','',$startAddress);
127
				$endAddress = preg_replace('/[^a-z]/i','',$endAddress);
128
				$returnValue = array();
129
				do {
130
					$returnValue[] = (integer) PHPExcel_Cell::columnIndexFromString($startAddress);
131
				} while ($startAddress++ != $endAddress);
132
				return $returnValue;
133
			} else {
134
				$cellAddress = preg_replace('/[^a-z]/i','',$cellAddress);
135
				return (integer) PHPExcel_Cell::columnIndexFromString($cellAddress);
136
			}
137
		}
138
	}	//	function COLUMN()
139
140
141
	/**
142
	 * COLUMNS
143
	 *
144
	 * Returns the number of columns in an array or reference.
145
	 *
146
	 * Excel Function:
147
	 *		=COLUMNS(cellAddress)
148
	 *
149
	 * @param	cellAddress		An array or array formula, or a reference to a range of cells for which you want the number of columns
150
	 * @return	integer			The number of columns in cellAddress
151
	 */
152 View Code Duplication
	public static function COLUMNS($cellAddress=Null) {
153
		if (is_null($cellAddress) || $cellAddress === '') {
154
			return 1;
155
		} elseif (!is_array($cellAddress)) {
156
			return PHPExcel_Calculation_Functions::VALUE();
157
		}
158
159
		$x = array_keys($cellAddress);
160
		$x = array_shift($x);
161
		$isMatrix = (is_numeric($x));
162
		list($columns,$rows) = PHPExcel_Calculation::_getMatrixDimensions($cellAddress);
163
164
		if ($isMatrix) {
165
			return $rows;
166
		} else {
167
			return $columns;
168
		}
169
	}	//	function COLUMNS()
170
171
172
	/**
173
	 * ROW
174
	 *
175
	 * Returns the row number of the given cell reference
176
	 * If the cell reference is a range of cells, ROW returns the row numbers of each row in the reference as a vertical array.
177
	 * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the
178
	 *		reference of the cell in which the ROW function appears; otherwise this function returns 0.
179
	 *
180
	 * Excel Function:
181
	 *		=ROW([cellAddress])
182
	 *
183
	 * @param	cellAddress		A reference to a range of cells for which you want the row numbers
184
	 * @return	integer or array of integer
185
	 */
186
	public static function ROW($cellAddress=Null) {
187
		if (is_null($cellAddress) || trim($cellAddress) === '') { return 0; }
188
189
		if (is_array($cellAddress)) {
190
			foreach($cellAddress as $columnKey => $rowValue) {
191
				foreach($rowValue as $rowKey => $cellValue) {
192
					return (integer) preg_replace('/[^0-9]/i','',$rowKey);
193
				}
194
			}
195 View Code Duplication
		} else {
196
			if (strpos($cellAddress,'!') !== false) {
197
				list($sheet,$cellAddress) = explode('!',$cellAddress);
0 ignored issues
show
Unused Code introduced by
The assignment to $sheet is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
198
			}
199
			if (strpos($cellAddress,':') !== false) {
200
				list($startAddress,$endAddress) = explode(':',$cellAddress);
201
				$startAddress = preg_replace('/[^0-9]/','',$startAddress);
202
				$endAddress = preg_replace('/[^0-9]/','',$endAddress);
203
				$returnValue = array();
204
				do {
205
					$returnValue[][] = (integer) $startAddress;
206
				} while ($startAddress++ != $endAddress);
207
				return $returnValue;
208
			} else {
209
				list($cellAddress) = explode(':',$cellAddress);
210
				return (integer) preg_replace('/[^0-9]/','',$cellAddress);
211
			}
212
		}
213
	}	//	function ROW()
214
215
216
	/**
217
	 * ROWS
218
	 *
219
	 * Returns the number of rows in an array or reference.
220
	 *
221
	 * Excel Function:
222
	 *		=ROWS(cellAddress)
223
	 *
224
	 * @param	cellAddress		An array or array formula, or a reference to a range of cells for which you want the number of rows
225
	 * @return	integer			The number of rows in cellAddress
226
	 */
227 View Code Duplication
	public static function ROWS($cellAddress=Null) {
228
		if (is_null($cellAddress) || $cellAddress === '') {
229
			return 1;
230
		} elseif (!is_array($cellAddress)) {
231
			return PHPExcel_Calculation_Functions::VALUE();
232
		}
233
234
		$i = array_keys($cellAddress);
235
		$isMatrix = (is_numeric(array_shift($i)));
236
		list($columns,$rows) = PHPExcel_Calculation::_getMatrixDimensions($cellAddress);
237
238
		if ($isMatrix) {
239
			return $columns;
240
		} else {
241
			return $rows;
242
		}
243
	}	//	function ROWS()
244
245
246
	/**
247
	 * HYPERLINK
248
	 *
249
	 * Excel Function:
250
	 *		=HYPERLINK(linkURL,displayName)
251
	 *
252
	 * @access	public
253
	 * @category Logical Functions
254
	 * @param	string	$linkURL		Value to check, is also the value returned when no error
255
	 * @param	string	$displayName	Value to return when testValue is an error condition
256
	 * @return	mixed	The value of $displayName (or $linkURL if $displayName was blank)
257
	 */
258
	public static function HYPERLINK($linkURL = '', $displayName = null, PHPExcel_Cell $pCell = null) {
0 ignored issues
show
Unused Code introduced by
The parameter $pCell is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
259
		$args = func_get_args();
260
		$pCell = array_pop($args);
261
262
		$linkURL		= (is_null($linkURL))		? '' :	PHPExcel_Calculation_Functions::flattenSingleValue($linkURL);
263
		$displayName	= (is_null($displayName))	? '' :	PHPExcel_Calculation_Functions::flattenSingleValue($displayName);
264
265
		if ((!is_object($pCell)) || (trim($linkURL) == '')) {
266
			return PHPExcel_Calculation_Functions::REF();
267
		}
268
269
		if ((is_object($displayName)) || trim($displayName) == '') {
270
			$displayName = $linkURL;
271
		}
272
273
		$pCell->getHyperlink()->setUrl($linkURL);
274
275
		return $displayName;
276
	}	//	function HYPERLINK()
277
278
279
	/**
280
	 * INDIRECT
281
	 *
282
	 * Returns the reference specified by a text string.
283
	 * References are immediately evaluated to display their contents.
284
	 *
285
	 * Excel Function:
286
	 *		=INDIRECT(cellAddress)
287
	 *
288
	 * NOTE - INDIRECT() does not yet support the optional a1 parameter introduced in Excel 2010
289
	 *
290
	 * @param	cellAddress		An array or array formula, or a reference to a range of cells for which you want the number of rows
291
	 * @return	mixed			The cells referenced by cellAddress
292
	 *
293
	 * @todo	Support for the optional a1 parameter introduced in Excel 2010
294
	 *
295
	 */
296
	public static function INDIRECT($cellAddress=Null, PHPExcel_Cell $pCell = null) {
297
		$cellAddress	= PHPExcel_Calculation_Functions::flattenSingleValue($cellAddress);
298
		if (is_null($cellAddress) || $cellAddress === '') {
299
			return PHPExcel_Calculation_Functions::REF();
300
		}
301
302
		$cellAddress1 = $cellAddress;
303
		$cellAddress2 = NULL;
304
		if (strpos($cellAddress,':') !== false) {
305
			list($cellAddress1,$cellAddress2) = explode(':',$cellAddress);
306
		}
307
308
		if ((!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $cellAddress1, $matches)) ||
309
			((!is_null($cellAddress2)) && (!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $cellAddress2, $matches)))) {
310
311
			if (!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $cellAddress1, $matches)) {
312
				return PHPExcel_Calculation_Functions::REF();
313
			}
314
315 View Code Duplication
			if (strpos($cellAddress,'!') !== false) {
316
				list($sheetName,$cellAddress) = explode('!',$cellAddress);
317
				$pSheet = $pCell->getParent()->getParent()->getSheetByName($sheetName);
0 ignored issues
show
Bug introduced by
It seems like $pCell is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
318
			} else {
319
				$pSheet = $pCell->getParent();
320
			}
321
322
			return PHPExcel_Calculation::getInstance()->extractNamedRange($cellAddress, $pSheet, False);
323
		}
324
325 View Code Duplication
		if (strpos($cellAddress,'!') !== false) {
326
			list($sheetName,$cellAddress) = explode('!',$cellAddress);
327
			$pSheet = $pCell->getParent()->getParent()->getSheetByName($sheetName);
328
		} else {
329
			$pSheet = $pCell->getParent();
330
		}
331
332
		return PHPExcel_Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, False);
333
	}	//	function INDIRECT()
334
335
336
	/**
337
	 * OFFSET
338
	 *
339
	 * Returns a reference to a range that is a specified number of rows and columns from a cell or range of cells.
340
	 * The reference that is returned can be a single cell or a range of cells. You can specify the number of rows and
341
	 * the number of columns to be returned.
342
	 *
343
	 * Excel Function:
344
	 *		=OFFSET(cellAddress, rows, cols, [height], [width])
345
	 *
346
	 * @param	cellAddress		The reference from which you want to base the offset. Reference must refer to a cell or
347
	 *								range of adjacent cells; otherwise, OFFSET returns the #VALUE! error value.
348
	 * @param	rows			The number of rows, up or down, that you want the upper-left cell to refer to.
349
	 *								Using 5 as the rows argument specifies that the upper-left cell in the reference is
350
	 *								five rows below reference. Rows can be positive (which means below the starting reference)
351
	 *								or negative (which means above the starting reference).
352
	 * @param	cols			The number of columns, to the left or right, that you want the upper-left cell of the result
353
	 *								to refer to. Using 5 as the cols argument specifies that the upper-left cell in the
354
	 *								reference is five columns to the right of reference. Cols can be positive (which means
355
	 *								to the right of the starting reference) or negative (which means to the left of the
356
	 *								starting reference).
357
	 * @param	height			The height, in number of rows, that you want the returned reference to be. Height must be a positive number.
358
	 * @param	width			The width, in number of columns, that you want the returned reference to be. Width must be a positive number.
359
	 * @return	string			A reference to a cell or range of cells
360
	 */
361
	public static function OFFSET($cellAddress=Null,$rows=0,$columns=0,$height=null,$width=null) {
362
		$rows		= PHPExcel_Calculation_Functions::flattenSingleValue($rows);
363
		$columns	= PHPExcel_Calculation_Functions::flattenSingleValue($columns);
364
		$height		= PHPExcel_Calculation_Functions::flattenSingleValue($height);
365
		$width		= PHPExcel_Calculation_Functions::flattenSingleValue($width);
366
		if ($cellAddress == Null) {
367
			return 0;
368
		}
369
370
		$args = func_get_args();
371
		$pCell = array_pop($args);
372
		if (!is_object($pCell)) {
373
			return PHPExcel_Calculation_Functions::REF();
374
		}
375
376
		$sheetName = null;
377
		if (strpos($cellAddress,"!")) {
378
			list($sheetName,$cellAddress) = explode("!",$cellAddress);
379
		}
380
		if (strpos($cellAddress,":")) {
381
			list($startCell,$endCell) = explode(":",$cellAddress);
382
		} else {
383
			$startCell = $endCell = $cellAddress;
384
		}
385
		list($startCellColumn,$startCellRow) = PHPExcel_Cell::coordinateFromString($startCell);
386
		list($endCellColumn,$endCellRow) = PHPExcel_Cell::coordinateFromString($endCell);
387
388
		$startCellRow += $rows;
389
		$startCellColumn = PHPExcel_Cell::columnIndexFromString($startCellColumn) - 1;
390
		$startCellColumn += $columns;
391
392
		if (($startCellRow <= 0) || ($startCellColumn < 0)) {
393
			return PHPExcel_Calculation_Functions::REF();
394
		}
395
		$endCellColumn = PHPExcel_Cell::columnIndexFromString($endCellColumn) - 1;
396
		if (($width != null) && (!is_object($width))) {
397
			$endCellColumn = $startCellColumn + $width - 1;
398
		} else {
399
			$endCellColumn += $columns;
400
		}
401
		$startCellColumn = PHPExcel_Cell::stringFromColumnIndex($startCellColumn);
402
403
		if (($height != null) && (!is_object($height))) {
404
			$endCellRow = $startCellRow + $height - 1;
405
		} else {
406
			$endCellRow += $rows;
407
		}
408
409
		if (($endCellRow <= 0) || ($endCellColumn < 0)) {
410
			return PHPExcel_Calculation_Functions::REF();
411
		}
412
		$endCellColumn = PHPExcel_Cell::stringFromColumnIndex($endCellColumn);
413
414
		$cellAddress = $startCellColumn.$startCellRow;
415
		if (($startCellColumn != $endCellColumn) || ($startCellRow != $endCellRow)) {
416
			$cellAddress .= ':'.$endCellColumn.$endCellRow;
417
		}
418
419
		if ($sheetName !== null) {
420
			$pSheet = $pCell->getParent()->getParent()->getSheetByName($sheetName);
421
		} else {
422
			$pSheet = $pCell->getParent();
423
		}
424
425
		return PHPExcel_Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, False);
426
	}	//	function OFFSET()
427
428
429
	/**
430
	 * CHOOSE
431
	 *
432
	 * Uses lookup_value to return a value from the list of value arguments.
433
	 * Use CHOOSE to select one of up to 254 values based on the lookup_value.
434
	 *
435
	 * Excel Function:
436
	 *		=CHOOSE(index_num, value1, [value2], ...)
437
	 *
438
	 * @param	index_num		Specifies which value argument is selected.
439
	 *							Index_num must be a number between 1 and 254, or a formula or reference to a cell containing a number
440
	 *								between 1 and 254.
441
	 * @param	value1...		Value1 is required, subsequent values are optional.
442
	 *							Between 1 to 254 value arguments from which CHOOSE selects a value or an action to perform based on
443
	 *								index_num. The arguments can be numbers, cell references, defined names, formulas, functions, or
444
	 *								text.
445
	 * @return	mixed			The selected value
446
	 */
447
	public static function CHOOSE() {
448
		$chooseArgs = func_get_args();
449
		$chosenEntry = PHPExcel_Calculation_Functions::flattenArray(array_shift($chooseArgs));
450
		$entryCount = count($chooseArgs) - 1;
451
452
		if(is_array($chosenEntry)) {
453
			$chosenEntry = array_shift($chosenEntry);
454
		}
455
		if ((is_numeric($chosenEntry)) && (!is_bool($chosenEntry))) {
456
			--$chosenEntry;
457
		} else {
458
			return PHPExcel_Calculation_Functions::VALUE();
459
		}
460
		$chosenEntry = floor($chosenEntry);
461
		if (($chosenEntry <= 0) || ($chosenEntry > $entryCount)) {
462
			return PHPExcel_Calculation_Functions::VALUE();
463
		}
464
465
		if (is_array($chooseArgs[$chosenEntry])) {
466
			return PHPExcel_Calculation_Functions::flattenArray($chooseArgs[$chosenEntry]);
467
		} else {
468
			return $chooseArgs[$chosenEntry];
469
		}
470
	}	//	function CHOOSE()
471
472
473
	/**
474
	 * MATCH
475
	 *
476
	 * The MATCH function searches for a specified item in a range of cells
477
	 *
478
	 * Excel Function:
479
	 *		=MATCH(lookup_value, lookup_array, [match_type])
480
	 *
481
	 * @param	lookup_value	The value that you want to match in lookup_array
482
	 * @param	lookup_array	The range of cells being searched
483
	 * @param	match_type		The number -1, 0, or 1. -1 means above, 0 means exact match, 1 means below. If match_type is 1 or -1, the list has to be ordered.
484
	 * @return	integer			The relative position of the found item
485
	 */
486
	public static function MATCH($lookup_value, $lookup_array, $match_type=1) {
487
		$lookup_array = PHPExcel_Calculation_Functions::flattenArray($lookup_array);
488
		$lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value);
489
		$match_type	= (is_null($match_type)) ? 1 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($match_type);
490
		//	MATCH is not case sensitive
491
		$lookup_value = strtolower($lookup_value);
492
493
		//	lookup_value type has to be number, text, or logical values
494 View Code Duplication
		if ((!is_numeric($lookup_value)) && (!is_string($lookup_value)) && (!is_bool($lookup_value))) {
495
			return PHPExcel_Calculation_Functions::NA();
496
		}
497
498
		//	match_type is 0, 1 or -1
499
		if (($match_type !== 0) && ($match_type !== -1) && ($match_type !== 1)) {
500
			return PHPExcel_Calculation_Functions::NA();
501
		}
502
503
		//	lookup_array should not be empty
504
		$lookupArraySize = count($lookup_array);
505
		if ($lookupArraySize <= 0) {
506
			return PHPExcel_Calculation_Functions::NA();
507
		}
508
509
		//	lookup_array should contain only number, text, or logical values, or empty (null) cells
510
		foreach($lookup_array as $i => $lookupArrayValue) {
511
			//	check the type of the value
512 View Code Duplication
			if ((!is_numeric($lookupArrayValue)) && (!is_string($lookupArrayValue)) &&
513
				(!is_bool($lookupArrayValue)) && (!is_null($lookupArrayValue))) {
514
				return PHPExcel_Calculation_Functions::NA();
515
			}
516
			//	convert strings to lowercase for case-insensitive testing
517
			if (is_string($lookupArrayValue)) {
518
				$lookup_array[$i] = strtolower($lookupArrayValue);
519
			}
520
			if ((is_null($lookupArrayValue)) && (($match_type == 1) || ($match_type == -1))) {
521
				$lookup_array = array_slice($lookup_array,0,$i-1);
522
			}
523
		}
524
525
		// if match_type is 1 or -1, the list has to be ordered
526
		if ($match_type == 1) {
527
			asort($lookup_array);
528
			$keySet = array_keys($lookup_array);
529
		} elseif($match_type == -1) {
530
			arsort($lookup_array);
531
			$keySet = array_keys($lookup_array);
532
		}
533
534
		// **
535
		// find the match
536
		// **
537
		// loop on the cells
538
//		var_dump($lookup_array);
539
//		echo '<br />';
540
		foreach($lookup_array as $i => $lookupArrayValue) {
541
			if (($match_type == 0) && ($lookupArrayValue == $lookup_value)) {
542
				//	exact match
543
				return ++$i;
544
			} elseif (($match_type == -1) && ($lookupArrayValue <= $lookup_value)) {
545
//				echo '$i = '.$i.' => ';
546
//				var_dump($lookupArrayValue);
547
//				echo '<br />';
548
//				echo 'Keyset = ';
549
//				var_dump($keySet);
550
//				echo '<br />';
551
				$i = array_search($i,$keySet);
0 ignored issues
show
Bug introduced by
The variable $keySet does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
552
//				echo '$i='.$i.'<br />';
553
				// if match_type is -1 <=> find the smallest value that is greater than or equal to lookup_value
554
				if ($i < 1){
555
					// 1st cell was allready smaller than the lookup_value
556
					break;
557
				} else {
558
					// the previous cell was the match
559
					return $keySet[$i-1]+1;
560
				}
561
			} elseif (($match_type == 1) && ($lookupArrayValue >= $lookup_value)) {
562
//				echo '$i = '.$i.' => ';
563
//				var_dump($lookupArrayValue);
564
//				echo '<br />';
565
//				echo 'Keyset = ';
566
//				var_dump($keySet);
567
//				echo '<br />';
568
				$i = array_search($i,$keySet);
569
//				echo '$i='.$i.'<br />';
570
				// if match_type is 1 <=> find the largest value that is less than or equal to lookup_value
571
				if ($i < 1){
572
					// 1st cell was allready bigger than the lookup_value
573
					break;
574
				} else {
575
					// the previous cell was the match
576
					return $keySet[$i-1]+1;
577
				}
578
			}
579
		}
580
581
		//	unsuccessful in finding a match, return #N/A error value
582
		return PHPExcel_Calculation_Functions::NA();
583
	}	//	function MATCH()
584
585
586
	/**
587
	 * INDEX
588
	 *
589
	 * Uses an index to choose a value from a reference or array
590
	 *
591
	 * Excel Function:
592
	 *		=INDEX(range_array, row_num, [column_num])
593
	 *
594
	 * @param	range_array		A range of cells or an array constant
595
	 * @param	row_num			The row in array from which to return a value. If row_num is omitted, column_num is required.
596
	 * @param	column_num		The column in array from which to return a value. If column_num is omitted, row_num is required.
597
	 * @return	mixed			the value of a specified cell or array of cells
598
	 */
599
	public static function INDEX($arrayValues,$rowNum = 0,$columnNum = 0) {
600
601
		if (($rowNum < 0) || ($columnNum < 0)) {
602
			return PHPExcel_Calculation_Functions::VALUE();
603
		}
604
605
		if (!is_array($arrayValues)) {
606
			return PHPExcel_Calculation_Functions::REF();
607
		}
608
609
		$rowKeys = array_keys($arrayValues);
610
		$columnKeys = @array_keys($arrayValues[$rowKeys[0]]);
611
612
		if ($columnNum > count($columnKeys)) {
613
			return PHPExcel_Calculation_Functions::VALUE();
614
		} elseif ($columnNum == 0) {
615
			if ($rowNum == 0) {
616
				return $arrayValues;
617
			}
618
			$rowNum = $rowKeys[--$rowNum];
619
			$returnArray = array();
620
			foreach($arrayValues as $arrayColumn) {
621
				if (is_array($arrayColumn)) {
622
					if (isset($arrayColumn[$rowNum])) {
623
						$returnArray[] = $arrayColumn[$rowNum];
624
					} else {
625
						return $arrayValues[$rowNum];
626
					}
627
				} else {
628
					return $arrayValues[$rowNum];
629
				}
630
			}
631
			return $returnArray;
632
		}
633
		$columnNum = $columnKeys[--$columnNum];
634
		if ($rowNum > count($rowKeys)) {
635
			return PHPExcel_Calculation_Functions::VALUE();
636
		} elseif ($rowNum == 0) {
637
			return $arrayValues[$columnNum];
638
		}
639
		$rowNum = $rowKeys[--$rowNum];
640
641
		return $arrayValues[$rowNum][$columnNum];
642
	}	//	function INDEX()
643
644
645
	/**
646
	 * TRANSPOSE
647
	 *
648
	 * @param	array	$matrixData	A matrix of values
649
	 * @return	array
650
	 *
651
	 * Unlike the Excel TRANSPOSE function, which will only work on a single row or column, this function will transpose a full matrix.
652
	 */
653
	public static function TRANSPOSE($matrixData) {
654
		$returnMatrix = array();
655
		if (!is_array($matrixData)) { $matrixData = array(array($matrixData)); }
656
657
		$column = 0;
658
		foreach($matrixData as $matrixRow) {
659
			$row = 0;
660
			foreach($matrixRow as $matrixCell) {
661
				$returnMatrix[$row][$column] = $matrixCell;
662
				++$row;
663
			}
664
			++$column;
665
		}
666
		return $returnMatrix;
667
	}	//	function TRANSPOSE()
668
669
670
	private static function _vlookupSort($a,$b) {
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
671
		$f = array_keys($a);
672
		$firstColumn = array_shift($f);
673
		if (strtolower($a[$firstColumn]) == strtolower($b[$firstColumn])) {
674
			return 0;
675
		}
676
		return (strtolower($a[$firstColumn]) < strtolower($b[$firstColumn])) ? -1 : 1;
677
	}	//	function _vlookupSort()
678
679
680
	/**
681
	* VLOOKUP
682
	* The VLOOKUP function searches for value in the left-most column of lookup_array and returns the value in the same row based on the index_number.
683
	* @param	lookup_value	The value that you want to match in lookup_array
684
	* @param	lookup_array	The range of cells being searched
685
	* @param	index_number	The column number in table_array from which the matching value must be returned. The first column is 1.
686
	* @param	not_exact_match	Determines if you are looking for an exact match based on lookup_value.
687
	* @return	mixed			The value of the found cell
688
	*/
689
	public static function VLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match=true) {
690
		$lookup_value	= PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value);
691
		$index_number	= PHPExcel_Calculation_Functions::flattenSingleValue($index_number);
692
		$not_exact_match	= PHPExcel_Calculation_Functions::flattenSingleValue($not_exact_match);
693
694
		// index_number must be greater than or equal to 1
695
		if ($index_number < 1) {
696
			return PHPExcel_Calculation_Functions::VALUE();
697
		}
698
699
		// index_number must be less than or equal to the number of columns in lookup_array
700
		if ((!is_array($lookup_array)) || (empty($lookup_array))) {
701
			return PHPExcel_Calculation_Functions::REF();
702
		} else {
703
			$f = array_keys($lookup_array);
704
			$firstRow = array_pop($f);
705
			if ((!is_array($lookup_array[$firstRow])) || ($index_number > count($lookup_array[$firstRow]))) {
706
				return PHPExcel_Calculation_Functions::REF();
707
			} else {
708
				$columnKeys = array_keys($lookup_array[$firstRow]);
709
				$returnColumn = $columnKeys[--$index_number];
710
				$firstColumn = array_shift($columnKeys);
711
			}
712
		}
713
714
		if (!$not_exact_match) {
715
			uasort($lookup_array,array('self','_vlookupSort'));
716
		}
717
718
		$rowNumber = $rowValue = False;
719
		foreach($lookup_array as $rowKey => $rowData) {
720
			if (strtolower($rowData[$firstColumn]) > strtolower($lookup_value)) {
721
				break;
722
			}
723
			$rowNumber = $rowKey;
724
			$rowValue = $rowData[$firstColumn];
725
		}
726
727
		if ($rowNumber !== false) {
728
			if ((!$not_exact_match) && ($rowValue != $lookup_value)) {
729
				//	if an exact match is required, we have what we need to return an appropriate response
730
				return PHPExcel_Calculation_Functions::NA();
731
			} else {
732
				//	otherwise return the appropriate value
733
				return $lookup_array[$rowNumber][$returnColumn];
734
			}
735
		}
736
737
		return PHPExcel_Calculation_Functions::NA();
738
	}	//	function VLOOKUP()
739
740
741
	/**
742
	 * LOOKUP
743
	 * The LOOKUP function searches for value either from a one-row or one-column range or from an array.
744
	 * @param	lookup_value	The value that you want to match in lookup_array
745
	 * @param	lookup_vector	The range of cells being searched
746
	 * @param	result_vector	The column from which the matching value must be returned
747
	 * @return	mixed			The value of the found cell
748
	 */
749
	public static function LOOKUP($lookup_value, $lookup_vector, $result_vector=null) {
750
		$lookup_value	= PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value);
751
752
		if (!is_array($lookup_vector)) {
753
			return PHPExcel_Calculation_Functions::NA();
754
		}
755
		$lookupRows = count($lookup_vector);
756
		$l = array_keys($lookup_vector);
757
		$l = array_shift($l);
758
		$lookupColumns = count($lookup_vector[$l]);
759 View Code Duplication
		if ((($lookupRows == 1) && ($lookupColumns > 1)) || (($lookupRows == 2) && ($lookupColumns != 2))) {
760
			$lookup_vector = self::TRANSPOSE($lookup_vector);
761
			$lookupRows = count($lookup_vector);
762
			$l = array_keys($lookup_vector);
763
			$lookupColumns = count($lookup_vector[array_shift($l)]);
764
		}
765
766
		if (is_null($result_vector)) {
767
			$result_vector = $lookup_vector;
768
		}
769
		$resultRows = count($result_vector);
770
		$l = array_keys($result_vector);
771
		$l = array_shift($l);
772
		$resultColumns = count($result_vector[$l]);
773 View Code Duplication
		if ((($resultRows == 1) && ($resultColumns > 1)) || (($resultRows == 2) && ($resultColumns != 2))) {
774
			$result_vector = self::TRANSPOSE($result_vector);
775
			$resultRows = count($result_vector);
776
			$r = array_keys($result_vector);
777
			$resultColumns = count($result_vector[array_shift($r)]);
778
		}
779
780
		if ($lookupRows == 2) {
781
			$result_vector = array_pop($lookup_vector);
782
			$lookup_vector = array_shift($lookup_vector);
783
		}
784
		if ($lookupColumns != 2) {
785
			foreach($lookup_vector as &$value) {
786
				if (is_array($value)) {
787
					$k = array_keys($value);
788
					$key1 = $key2 = array_shift($k);
789
					$key2++;
790
					$dataValue1 = $value[$key1];
791
				} else {
792
					$key1 = 0;
793
					$key2 = 1;
794
					$dataValue1 = $value;
795
				}
796
				$dataValue2 = array_shift($result_vector);
797
				if (is_array($dataValue2)) {
798
					$dataValue2 = array_shift($dataValue2);
799
				}
800
				$value = array($key1 => $dataValue1, $key2 => $dataValue2);
801
			}
802
			unset($value);
803
		}
804
805
		return self::VLOOKUP($lookup_value,$lookup_vector,2);
806
 	}	//	function LOOKUP()
807
808
}	//	class PHPExcel_Calculation_LookupRef
809