Passed
Push — master ( 6d0871...96ed97 )
by Fabio
05:41
created

TPriorityMap::add()   C

Complexity

Conditions 12
Paths 36

Size

Total Lines 34
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 12
eloc 24
c 1
b 0
f 0
nc 36
nop 3
dl 0
loc 34
rs 6.9666
ccs 17
cts 17
cp 1
crap 12

How to fix   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
 * TPriorityMap, TPriorityMapIterator classes
4
 *
5
 * @author Brad Anderson <[email protected]>
6
 * @link https://github.com/pradosoft/prado
7
 * @license https://github.com/pradosoft/prado/blob/master/LICENSE
8
 */
9
10
namespace Prado\Collections;
11
12
use Prado\Exceptions\TInvalidOperationException;
13
use Prado\Exceptions\TInvalidDataTypeException;
14
use Prado\TPropertyValue;
15
16
/**
17
 * TPriorityMap class
18
 *
19
 * TPriorityMap implements a collection that takes key-value pairs with
20
 * a priority to allow key-value pairs to be ordered.  This ordering is
21
 * important when flattening the map. When flattening the map, if some
22
 * key-value pairs are required to be before or after others, use this
23
 * class to keep order to your map.
24
 *
25
 * You can access, add or remove an item with a key by using
26
 * {@link itemAt}, {@link add}, and {@link remove}.  These functions
27
 * can optionally take a priority parameter to allow access to specific
28
 * priorities.  TPriorityMap is functionally backward compatible
29
 * with {@link TMap}.
30
 *
31
 * To get the number of the items in the map, use {@link getCount}.
32
 * TPriorityMap can also be used like a regular array as follows,
33
 * <code>
34
 * $map[$key]=$value; // add a key-value pair
35
 * unset($map[$key]); // remove the value with the specified key
36
 * if(isset($map[$key])) // if the map contains the key
37
 * foreach($map as $key=>$value) // traverse the items in the map
38
 * $n=count($map);  // returns the number of items in the map
39
 * </code>
40
 * Using standard array access method like these will always use
41
 * the default priority.
42
 *
43
 * An item that doesn't specify a priority will receive the default
44
 * priority.  The default priority is set during the instantiation
45
 * of a new TPriorityMap. If no custom default priority is specified,
46
 * the standard default priority of 10 is used.
47
 *
48
 * Priorities with significant digits below precision will be rounded.
49
 *
50
 * A priority may also be a numeric with decimals.  This is set
51
 * during the instantiation of a new TPriorityMap.
52
 * The default is 8 decimal places for a priority.  If a negative number
53
 * is used, rounding occurs into the integer space rather than in
54
 * the decimal space.  See {@link round}.
55
 *
56
 * @author Brad Anderson <[email protected]>
57
 * @since 3.2a
58
 * @method void dyAddItem(mixed $key, mixed $value)
59
 * @method void dyRemoveItem(mixed $key, mixed $value)
60
 * @method mixed dyNoItem(mixed $returnValue, mixed $key)
61
 */
62
class TPriorityMap extends TMap
63
{
64
	/**
65
	 * @var bool indicates if the _d is currently ordered.
66
	 */
67
	private $_o = false;
68
	/**
69
	 * @var null|array cached flattened internal data storage
70
	 */
71
	private $_fd;
72
	/**
73
	 * @var int number of items contain within the map
74
	 */
75
	private $_c = 0;
76
	/**
77
	 * @var numeric the default priority of items without specified priorities
0 ignored issues
show
Bug introduced by
The type Prado\Collections\numeric was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
78
	 */
79
	private $_dp = 10;
80
	/**
81
	 * @var int the precision of the numeric priorities within this priority list.
82
	 */
83
	private $_p = 8;
84
85
	/**
86
	 * Constructor.
87
	 * Initializes the array with an array or an iterable object.
88
	 * @param null|array|TPriorityMap|\Traversable $data the intial data. Default is null, meaning no initialization.
89
	 * @param bool $readOnly whether the list is read-only
90
	 * @param numeric $defaultPriority the default priority of items without specified priorities.
91
	 * @param int $precision the precision of the numeric priorities
92
	 * @throws TInvalidDataTypeException If data is not null and neither an array nor an iterator.
93
	 */
94 53
	public function __construct($data = null, $readOnly = false, $defaultPriority = 10, $precision = 8)
95
	{
96 53
		parent::__construct();
97 4
		if ($data !== null) {
98
			$this->copyFrom($data);
99 53
		}
100 53
		$this->setReadOnly($readOnly);
101 53
		$this->setPrecision($precision);
102 53
		$this->setDefaultPriority($defaultPriority);
0 ignored issues
show
Bug introduced by
It seems like $defaultPriority can also be of type integer; however, parameter $value of Prado\Collections\TPrior...p::setDefaultPriority() does only seem to accept Prado\Collections\numeric, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

102
		$this->setDefaultPriority(/** @scrutinizer ignore-type */ $defaultPriority);
Loading history...
103
	}
104
105
	/**
106
	 * @return numeric gets the default priority of inserted items without a specified priority
107 53
	 */
108
	public function getDefaultPriority()
109 53
	{
110
		return $this->_dp;
111
	}
112
113
	/**
114
	 * This must be called internally or when instantiated.
115
	 * @param numeric $value sets the default priority of inserted items without a specified priority
116 53
	 */
117
	protected function setDefaultPriority($value)
118 53
	{
119 53
		$this->_dp = (string) round(TPropertyValue::ensureFloat($value), $this->_p);
0 ignored issues
show
Documentation Bug introduced by
It seems like (string)round(Prado\TPro...oat($value), $this->_p) of type string is incompatible with the declared type Prado\Collections\numeric of property $_dp.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
120
	}
121
122
	/**
123
	 * @return int The precision of numeric priorities, defaults to 8
124 2
	 */
125
	public function getPrecision()
126 2
	{
127
		return $this->_p;
128
	}
129
130
	/**
131
	 * This must be called internally or when instantiated.
132
	 * @param int $value The precision of numeric priorities.
133 53
	 */
134
	protected function setPrecision($value)
135 53
	{
136 53
		$this->_p = TPropertyValue::ensureInteger($value);
137
	}
138
139
	/**
140
	 * Takes an input Priority and ensures its value.
141
	 * Sets the default $priority when none is set,
142
	 * then rounds to the proper precision and makes
143 2
	 * into a string.
144
	 * @param null|numeric $priority the priority to ensure
145 2
	 * @return string the priority in string format
146
	 */
147
	protected function ensurePriority($priority): string
148
	{
149
		if ($priority === null || !is_numeric($priority)) {
0 ignored issues
show
introduced by
The condition is_numeric($priority) is always false.
Loading history...
150
			$priority = $this->getDefaultPriority();
151
		}
152 48
		return (string) round(TPropertyValue::ensureFloat($priority), $this->_p);
153
	}
154 48
155 48
	/**
156 48
	 * Returns an iterator for traversing the items in the map.
157
	 * This method is required by the interface \IteratorAggregate.
158 48
	 * @return \Iterator an iterator for traversing the items in the map.
159
	 */
160
	#[\ReturnTypeWillChange]
161
	public function getIterator()
162
	{
163
		return new \ArrayIterator($this->flattenPriorities());
164 42
	}
165
166 42
167 34
	/**
168
	 * Orders the priority list internally.
169
	 */
170 42
	protected function sortPriorities()
171 42
	{
172 42
		if (!$this->_o) {
173 41
			ksort($this->_d, SORT_NUMERIC);
174
			$this->_o = true;
175 42
		}
176
	}
177
178
	/**
179
	 * This flattens the priority map into a flat array [0,...,n-1]
180
	 * @return array array of items in the list in priority and index order
181 20
	 */
182
	protected function flattenPriorities()
183 20
	{
184
		if (is_array($this->_fd)) {
185
			return $this->_fd;
186
		}
187
188
		$this->sortPriorities();
189
		$this->_fd = [];
190
		foreach ($this->_d as $priority => $itemsatpriority) {
191
			$this->_fd = array_merge($this->_fd, $itemsatpriority);
192
		}
193
		return $this->_fd;
194
	}
195
196
	/**
197
	 * @return int the number of items in the map
198
	 */
199
	public function getCount()
200
	{
201
		return $this->_c;
202
	}
203
204
	/**
205
	 * Gets the number of items at a priority within the map.
206
	 * @param null|numeric $priority optional priority at which to count items.  if no parameter,
207
	 * it will be set to the default {@link getDefaultPriority}
208
	 * @return false|int the number of items in the map at the specified priority
209 3
	 */
210
	public function getPriorityCount($priority = null)
211 3
	{
212 3
		$priority = $this->ensurePriority($priority);
213
		if (!isset($this->_d[$priority]) || !is_array($this->_d[$priority])) {
214
			return false;
215
		}
216
		return count($this->_d[$priority]);
217
	}
218
219 1
	/**
220
	 * This returns a list of the priorities within this map, ordered lowest to highest.
221 1
	 * @return array the array of priority numerics in decreasing priority order
222
	 */
223
	public function getPriorities()
224
	{
225
		$this->sortPriorities();
226
		return array_keys($this->_d);
227
	}
228
229
	/**
230
	 * Returns the keys within the map ordered through the priority of each key-value pair
231
	 * @return array the key list
232 29
	 */
233
	public function getKeys()
234 29
	{
235 29
		return array_keys($this->flattenPriorities());
236 29
	}
237
238 1
	/**
239
	 * Returns the item with the specified key.  If a priority is specified, only items
240
	 * within that specific priority will be selected
241 1
	 * @param mixed $key the key
242 1
	 * @param mixed $priority the priority.  null is the default priority, false is any priority,
243
	 * and numeric is a specific priority.  default: false, any priority.
244
	 * @return mixed the element at the offset, null if no element is found at the offset
245
	 */
246
	public function itemAt($key, $priority = false)
247
	{
248
		if ($priority === false) {
249
			$map = $this->flattenPriorities();
250
			return array_key_exists($key, $map) ? $map[$key] : $this->dyNoItem(null, $key);
251
		} else {
252
			$priority = $this->ensurePriority($priority);
253 1
			return (isset($this->_d[$priority]) && array_key_exists($key, $this->_d[$priority])) ? $this->_d[$priority][$key] : $this->dyNoItem(null, $key);
254
		}
255 1
	}
256 1
257
	/**
258 1
	 * This changes an item's priority.  Specify the item and the new priority.
259
	 * This method is exactly the same as {@link offsetGet}.
260 1
	 * @param mixed $key the key
261 1
	 * @param null|numeric $priority the priority.  default: null, filled in with the default priority numeric.
262 1
	 * @return numeric old priority of the item
263 1
	 */
264
	public function setPriorityAt($key, $priority = null)
265 1
	{
266
		$priority = $this->ensurePriority($priority);
267
		$oldpriority = $this->priorityAt($key);
268
		if ($oldpriority !== false && $oldpriority != $priority) {
0 ignored issues
show
introduced by
The condition $oldpriority !== false is always false.
Loading history...
269
			$value = $this->remove($key, $oldpriority);
270
			$this->add($key, $value, $priority);
271
		}
272
		return $oldpriority;
273 3
	}
274
275 3
	/**
276
	 * Gets all the items at a specific priority.
277
	 * @param null|numeric $priority priority of the items to get.  Defaults to null, filled in with the default priority, if left blank.
278 3
	 * @return array all items at priority in index order, null if there are no items at that priority
279
	 */
280 3
	public function itemsAtPriority($priority = null)
281
	{
282
		$priority = $this->ensurePriority($priority);
283
		return $this->_d[$priority] ?? null;
284
	}
285
286
	/**
287
	 * Returns the priority of a particular item within the map.  This searches the map for the item.
288 2
	 * @param mixed $item item to look for within the map
289
	 * @return false|numeric priority of the item in the map
290 2
	 */
291 2
	public function priorityOf($item)
292 2
	{
293 2
		$this->sortPriorities();
294
		foreach ($this->_d as $priority => $items) {
295
			if (($index = array_search($item, $items, true)) !== false) {
0 ignored issues
show
Unused Code introduced by
The assignment to $index is dead and can be removed.
Loading history...
296 1
				return $priority;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $priority returns the type integer|string which is incompatible with the documented return type Prado\Collections\numeric|false.
Loading history...
297
			}
298
		}
299
		return false;
300
	}
301
302
	/**
303
	 * Retutrns the priority of an item at a particular flattened index.
304 3
	 * @param int $key index of the item within the map
305
	 * @return false|numeric priority of the item in the map
306 3
	 */
307 3
	public function priorityAt($key)
308 3
	{
309 3
		$this->sortPriorities();
310
		foreach ($this->_d as $priority => $items) {
311
			if (array_key_exists($key, $items)) {
312 1
				return $priority;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $priority returns the type integer|string which is incompatible with the documented return type Prado\Collections\numeric|false.
Loading history...
313
			}
314
		}
315
		return false;
316
	}
317
318
	/**
319
	 * Adds an item into the map.  A third parameter may be used to set the priority
320
	 * of the item within the map.  Priority is primarily used during when flattening
321
	 * the map into an array where order may be and important factor of the key-value
322
	 * pairs within the array.
323
	 * Note, if the specified key already exists, the old value will be overwritten.
324
	 * No duplicate keys are allowed regardless of priority.
325
	 * @param mixed $key
326
	 * @param mixed $value
327
	 * @param null|numeric $priority default: null, filled in with default priority
328 53
	 * @throws TInvalidOperationException if the map is read-only
329
	 * @return numeric priority at which the pair was added
330 53
	 */
331 53
	public function add($key, $value, $priority = null)
332
	{
333 53
		$itemPriority = null;
334
		if (($isPriorityItem = ($value instanceof IPriorityItem)) && ($priority === null || !is_numeric($priority))) {
335 53
			$itemPriority = $priority = $value->getPriority();
336 53
		}
337 36
		$priority = $this->ensurePriority($priority);
338 4
		if (($value instanceof IPriorityCapture) && (!$isPriorityItem || $itemPriority !== $priority)) {
339 4
			$value->setPriority($priority);
0 ignored issues
show
Bug introduced by
$priority of type string is incompatible with the type Prado\Collections\numeric expected by parameter $value of Prado\Collections\IPriorityCapture::setPriority(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

339
			$value->setPriority(/** @scrutinizer ignore-type */ $priority);
Loading history...
340 4
		}
341 36
342
		if (!$this->_r) {
343
			foreach ($this->_d as $innerpriority => $items) {
344
				if (array_key_exists($key, $items)) {
345 53
					unset($this->_d[$innerpriority][$key]);
346 53
					$this->_c--;
347 53
					if (count($this->_d[$innerpriority]) === 0) {
348
						unset($this->_d[$innerpriority]);
349 36
					}
350
				}
351 53
			}
352 53
			if (!isset($this->_d[$priority])) {
353
				$this->_d[$priority] = [$key => $value];
354 1
				$this->_o = false;
355
			} else {
356 53
				$this->_d[$priority][$key] = $value;
357
			}
358
			$this->_c++;
359
			$this->_fd = null;
360
			$this->dyAddItem($key, $value);
361
		} else {
362
			throw new TInvalidOperationException('map_readonly', get_class($this));
363
		}
364
		return $priority;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $priority returns the type string which is incompatible with the documented return type Prado\Collections\numeric.
Loading history...
365
	}
366
367
	/**
368
	 * Removes an item from the map by its key. If no priority, or false, is specified
369
	 * then priority is irrelevant. If null is used as a parameter for priority, then
370
	 * the priority will be the default priority.  If a priority is specified, or
371 26
	 * the default priority is specified, only key-value pairs in that priority
372
	 * will be affected.
373 26
	 * @param mixed $key the key of the item to be removed
374 25
	 * @param null|false|numeric $priority priority.  False is any priority, null is the
375 7
	 * default priority, and numeric is a specific priority
376
	 * @throws TInvalidOperationException if the map is read-only
377
	 * @return mixed the removed value, null if no such key exists.
378 25
	 */
379 19
	public function remove($key, $priority = false)
380 19
	{
381 19
		if (!$this->_r) {
382 19
			if ($priority === false) {
383 19
				$this->sortPriorities();
384 19
				foreach ($this->_d as $priority => $items) {
385 19
					if (array_key_exists($key, $items)) {
386 14
						$value = $this->_d[$priority][$key];
387 14
						unset($this->_d[$priority][$key]);
388
						$this->_c--;
389 19
						if (count($this->_d[$priority]) === 0) {
390 19
							unset($this->_d[$priority]);
391
							$this->_o = false;
392
						}
393 2
						$this->_fd = null;
394
						$this->dyRemoveItem($key, $value);
395 8
						return $value;
396 8
					}
397 7
				}
398 7
				return null;
399 7
			} else {
400 7
				$priority = $this->ensurePriority($priority);
401 6
				if (isset($this->_d[$priority]) && (isset($this->_d[$priority][$key]) || array_key_exists($key, $this->_d[$priority]))) {
402 6
					$value = $this->_d[$priority][$key];
403
					unset($this->_d[$priority][$key]);
404 7
					$this->_c--;
405 7
					if (count($this->_d[$priority]) === 0) {
406
						unset($this->_d[$priority]);
407 1
						$this->_o = false;
408
					}
409
					$this->_fd = null;
410
					$this->dyRemoveItem($key, $value);
411 1
					return $value;
412
				} else {
413
					return null;
414
				}
415
			}
416
		} else {
417
			throw new TInvalidOperationException('map_readonly', get_class($this));
418 3
		}
419
	}
420 3
421 3
	/**
422 3
	 * Removes all items in the map.  {@link remove} is called on all items.
423
	 */
424
	public function clear()
425 3
	{
426
		foreach ($this->_d as $priority => $items) {
427
			foreach (array_keys($items) as $key) {
428
				$this->remove($key);
429
			}
430
		}
431 31
	}
432
433 31
	/**
434 31
	 * @param mixed $key the key
435
	 * @return bool whether the map contains an item with the specified key
436
	 */
437
	public function contains($key)
438
	{
439
		$map = $this->flattenPriorities();
440
		return isset($map[$key]) || array_key_exists($key, $map);
441
	}
442
443 30
	/**
444
	 * When the map is flattened into an array, the priorities are taken into
445 30
	 * account and elements of the map are ordered in the array according to
446
	 * their priority.
447
	 * @return array the list of items in array
448
	 */
449
	public function toArray()
450
	{
451
		return $this->flattenPriorities();
452
	}
453
454
	/**
455 1
	 * Combines the map elements which have a priority below the parameter value
456
	 * @param numeric $priority the cut-off priority.  All items of priority less than this are returned.
457 1
	 * @param bool $inclusive whether or not the input cut-off priority is inclusive.  Default: false, not inclusive.
458 1
	 * @return array the array of priorities keys with values of arrays of items that are below a specified priority.
459 1
	 *  The priorities are sorted so important priorities, lower numerics, are first.
460 1
	 */
461 1
	public function toArrayBelowPriority($priority, $inclusive = false)
462
	{
463 1
		$this->sortPriorities();
464
		$items = [];
465 1
		foreach ($this->_d as $itemspriority => $itemsatpriority) {
466
			if ((!$inclusive && $itemspriority >= $priority) || $itemspriority > $priority) {
467
				break;
468
			}
469
			$items = array_merge($items, $itemsatpriority);
470
		}
471
		return $items;
472
	}
473
474
	/**
475 1
	 * Combines the map elements which have a priority above the parameter value
476
	 * @param numeric $priority the cut-off priority.  All items of priority greater than this are returned.
477 1
	 * @param bool $inclusive whether or not the input cut-off priority is inclusive.  Default: true, inclusive.
478 1
	 * @return array the array of priorities keys with values of arrays of items that are above a specified priority.
479 1
	 *  The priorities are sorted so important priorities, lower numerics, are first.
480 1
	 */
481 1
	public function toArrayAbovePriority($priority, $inclusive = true)
482
	{
483 1
		$this->sortPriorities();
484
		$items = [];
485 1
		foreach ($this->_d as $itemspriority => $itemsatpriority) {
486
			if ((!$inclusive && $itemspriority <= $priority) || $itemspriority < $priority) {
487
				continue;
488
			}
489
			$items = array_merge($items, $itemsatpriority);
490
		}
491
		return $items;
492
	}
493
494 6
	/**
495
	 * Copies iterable data into the map.
496 6
	 * Note, existing data in the map will be cleared first.
497 2
	 * @param array|TPriorityMap|\Traversable $data the data to be copied from, must be an array, object implementing
498 1
	 * @throws TInvalidDataTypeException If data is neither an array nor an iterator.
499
	 */
500 2
	public function copyFrom($data)
501 2
	{
502 2
		if ($data instanceof TPriorityMap) {
503
			if ($this->getCount() > 0) {
504
				$this->clear();
505 5
			}
506 5
			foreach ($data->getPriorities() as $priority) {
507 1
				foreach ($data->itemsAtPriority($priority) as $key => $value) {
508
					$this->add($key, $value, $priority);
509 5
				}
510 5
			}
511
		} elseif (is_array($data) || $data instanceof \Traversable) {
0 ignored issues
show
introduced by
$data is always a sub-type of Traversable.
Loading history...
512 1
			if ($this->getCount() > 0) {
513 1
				$this->clear();
514
			}
515 6
			foreach ($data as $key => $value) {
516
				$this->add($key, $value);
517
			}
518
		} elseif ($data !== null) {
519
			throw new TInvalidDataTypeException('map_data_not_iterable');
520
		}
521
	}
522
523
	/**
524 2
	 * Merges iterable data into the map.
525
	 * Existing data in the map will be kept and overwritten if the keys are the same.
526 2
	 * @param array|TPriorityMap|\Traversable $data the data to be merged with, must be an array,
527 1
	 * object implementing Traversable, or a TPriorityMap
528 1
	 * @throws TInvalidDataTypeException If data is neither an array nor an iterator.
529 1
	 */
530
	public function mergeWith($data)
531
	{
532 1
		if ($data instanceof TPriorityMap) {
533 1
			foreach ($data->getPriorities() as $priority) {
534 1
				foreach ($data->itemsAtPriority($priority) as $key => $value) {
535
					$this->add($key, $value, $priority);
536 1
				}
537 1
			}
538
		} elseif (is_array($data) || $data instanceof \Traversable) {
0 ignored issues
show
introduced by
$data is always a sub-type of Traversable.
Loading history...
539 2
			foreach ($data as $key => $value) {
540
				$this->add($key, $value);
541
			}
542
		} elseif ($data !== null) {
543
			throw new TInvalidDataTypeException('map_data_not_iterable');
544
		}
545
	}
546
}
547