|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* This file is part of the sauls/helpers package. |
|
4
|
|
|
* |
|
5
|
|
|
* @author Saulius Vaičeliūnas <[email protected]> |
|
6
|
|
|
* @link http://saulius.vaiceliunas.lt |
|
7
|
|
|
* @copyright 2018 |
|
8
|
|
|
* |
|
9
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
10
|
|
|
* file that was distributed with this source code. |
|
11
|
|
|
*/ |
|
12
|
|
|
|
|
13
|
|
|
namespace Sauls\Component\Helper\Operation\ArrayOperation; |
|
14
|
|
|
|
|
15
|
|
|
class DeepSearch implements DeepSearchInterface |
|
16
|
|
|
{ |
|
17
|
|
|
/** |
|
18
|
|
|
* @var FlattenInterface |
|
19
|
|
|
*/ |
|
20
|
|
|
private $arrayFlattenOperation; |
|
21
|
|
|
/** |
|
22
|
|
|
* @var MergeInterface |
|
23
|
|
|
*/ |
|
24
|
|
|
private $arrayMergeOperation; |
|
25
|
|
|
|
|
26
|
1 |
|
public function __construct(FlattenInterface $arrayFlattenOperation, MergeInterface $arrayMergeOperation) |
|
27
|
|
|
{ |
|
28
|
|
|
|
|
29
|
1 |
|
$this->arrayFlattenOperation = $arrayFlattenOperation; |
|
30
|
1 |
|
$this->arrayMergeOperation = $arrayMergeOperation; |
|
31
|
1 |
|
} |
|
32
|
|
|
|
|
33
|
5 |
|
public function execute(array $array, $searchValue): array |
|
34
|
|
|
{ |
|
35
|
5 |
|
$foundedValueArrayPath = []; |
|
36
|
5 |
|
foreach ($array as $key => $value) { |
|
37
|
4 |
|
if ($path = $this->deepSearchValuePath([$key, $value], $searchValue)) { |
|
38
|
3 |
|
$foundedValueArrayPath[] = $path; |
|
39
|
|
|
} |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
5 |
|
return $foundedValueArrayPath; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
4 |
|
private function deepSearchValuePath(array $parameters, $searchValue, $path = []) |
|
46
|
|
|
{ |
|
47
|
4 |
|
[$key, $value] = $parameters; |
|
48
|
|
|
|
|
49
|
4 |
|
if (\is_array($value) && $subPath = $this->execute($value, $searchValue)) { |
|
50
|
2 |
|
return $this->arrayFlattenOperation->execute( |
|
51
|
2 |
|
$this->arrayMergeOperation->execute($path, [$key], $subPath) |
|
52
|
|
|
); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
4 |
|
if ($value === $searchValue) { |
|
56
|
3 |
|
return [$key]; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
4 |
|
return []; |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|