1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
/** |
3
|
|
|
* This file is part of the Phootwork package. |
4
|
|
|
* For the full copyright and license information, please view the LICENSE |
5
|
|
|
* file that was distributed with this source code. |
6
|
|
|
* |
7
|
|
|
* @license MIT License |
8
|
|
|
* @copyright Thomas Gossmann |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace phootwork\lang\parts; |
12
|
|
|
|
13
|
|
|
trait IndexFindersPart { |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Returns the index of the given element or false if the element can't be found |
17
|
|
|
* |
18
|
|
|
* @param mixed $element |
19
|
|
|
* @return int the index for the given element |
20
|
|
|
*/ |
21
|
4 |
|
public function indexOf($element): ?int { |
22
|
4 |
|
$out = array_search($element, $this->array, true); |
23
|
|
|
|
24
|
4 |
|
return false === $out ? null : $out; |
|
|
|
|
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Searches the array with a given callback and returns the index for the last element if found. |
29
|
|
|
* |
30
|
|
|
* The callback function takes one or two parameters: |
31
|
|
|
* |
32
|
|
|
* function ($element [, $query]) {} |
33
|
|
|
* |
34
|
|
|
* The callback must return a boolean |
35
|
|
|
* When it's passed, $query must be the first argument: |
36
|
|
|
* |
37
|
|
|
* - find($query, callback) |
38
|
|
|
* - find(callback) |
39
|
|
|
* |
40
|
|
|
* @param array $arguments |
41
|
|
|
* @return int|null the index or null if it hasn't been found |
42
|
|
|
*/ |
43
|
2 |
|
public function findLastIndex(...$arguments): ?int { |
44
|
2 |
|
$index = count($arguments) === 1 ? |
45
|
2 |
|
$this->findLast($arguments[0]) : $this->findLast($arguments[0], $arguments[1]); |
|
|
|
|
46
|
|
|
|
47
|
2 |
|
return $this->indexOf($index); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* Searches the array with a given callback and returns the index for the first element if found. |
52
|
|
|
* |
53
|
|
|
* The callback function takes one or two parameters: |
54
|
|
|
* |
55
|
|
|
* function ($element [, $query]) {} |
56
|
|
|
* |
57
|
|
|
* The callback must return a boolean |
58
|
|
|
* When it's passed, $query must be the first argument: |
59
|
|
|
* |
60
|
|
|
* - find($query, callback) |
61
|
|
|
* - find(callback) |
62
|
|
|
* |
63
|
|
|
* @param array $arguments |
64
|
|
|
* @return int|null the index or null if it hasn't been found |
65
|
|
|
*/ |
66
|
2 |
|
public function findIndex(...$arguments): ?int { |
67
|
2 |
|
$index = count($arguments) === 1 ? $this->find($arguments[0]) : $this->find($arguments[0], $arguments[1]); |
|
|
|
|
68
|
|
|
|
69
|
2 |
|
return $this->indexOf($index); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|