1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace PeeHaa\ArrayPath; |
4
|
|
|
|
5
|
|
|
class ArrayPath |
6
|
|
|
{ |
7
|
|
|
private $delimiter; |
8
|
|
|
|
9
|
12 |
|
public function __construct($delimiter = '.') |
10
|
|
|
{ |
11
|
12 |
|
$this->delimiter = $delimiter; |
12
|
12 |
|
} |
13
|
|
|
|
14
|
5 |
|
public function get(array $source, string $path) |
15
|
|
|
{ |
16
|
5 |
|
$keys = explode($this->delimiter, $path); |
17
|
|
|
|
18
|
5 |
|
$currentSource = $source; |
19
|
|
|
|
20
|
5 |
|
foreach ($keys as $key) { |
21
|
5 |
|
if (!array_key_exists($key, $currentSource)) { |
22
|
2 |
|
throw new NotFoundException(); |
23
|
|
|
} |
24
|
|
|
|
25
|
4 |
|
$currentSource = $currentSource[$key]; |
26
|
|
|
} |
27
|
|
|
|
28
|
3 |
|
return $currentSource; |
29
|
|
|
} |
30
|
|
|
|
31
|
4 |
View Code Duplication |
public function set(array &$source, string $path, $value): void |
|
|
|
|
32
|
|
|
{ |
33
|
4 |
|
$keys = explode($this->delimiter, $path); |
34
|
|
|
|
35
|
4 |
|
$currentSource = &$source; |
36
|
|
|
|
37
|
4 |
|
foreach ($keys as $key) { |
38
|
4 |
|
if (!array_key_exists($key, $currentSource)) { |
39
|
3 |
|
$currentSource[$key] = []; |
40
|
|
|
} |
41
|
|
|
|
42
|
4 |
|
$currentSource = &$currentSource[$key]; |
43
|
|
|
} |
44
|
|
|
|
45
|
4 |
|
$currentSource = $value; |
46
|
4 |
|
} |
47
|
|
|
|
48
|
2 |
|
public function exists(array $source, string $path): bool |
49
|
|
|
{ |
50
|
|
|
try { |
51
|
2 |
|
$this->get($source, $path); |
52
|
1 |
|
} catch (NotFoundException $e) { |
53
|
1 |
|
return false; |
54
|
|
|
} |
55
|
|
|
|
56
|
1 |
|
return true; |
57
|
|
|
} |
58
|
|
|
|
59
|
3 |
View Code Duplication |
public function remove(array &$source, string $path): void |
|
|
|
|
60
|
|
|
{ |
61
|
3 |
|
$keys = explode($this->delimiter, $path); |
62
|
|
|
|
63
|
3 |
|
$lastKey = array_pop($keys); |
64
|
|
|
|
65
|
3 |
|
$currentSource = &$source; |
66
|
|
|
|
67
|
3 |
|
foreach ($keys as $key) { |
68
|
3 |
|
if (!array_key_exists($key, $currentSource)) { |
69
|
1 |
|
return; |
70
|
|
|
} |
71
|
|
|
|
72
|
3 |
|
$currentSource = &$currentSource[$key]; |
73
|
|
|
} |
74
|
|
|
|
75
|
2 |
|
unset($currentSource[$lastKey]); |
76
|
2 |
|
} |
77
|
|
|
} |
78
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.