1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Stratadox\TableLoader\Loader; |
5
|
|
|
|
6
|
|
|
use function array_filter as filtered; |
7
|
|
|
use function array_map as andMapped; |
8
|
|
|
use function strlen as lengthOf; |
9
|
|
|
use function strpos as positionOf; |
10
|
|
|
use function substr as aPortionOf; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Limits the data set to the relevant subset. |
14
|
|
|
* |
15
|
|
|
* @author Stratadox |
16
|
|
|
*/ |
17
|
|
|
final class Prefixed implements FiltersTheArray |
18
|
|
|
{ |
19
|
|
|
private $label; |
20
|
|
|
private $prefix; |
21
|
|
|
private $startingAt; |
22
|
|
|
|
23
|
|
|
private function __construct(string $label, string $separator) |
24
|
|
|
{ |
25
|
|
|
$this->label = $label; |
26
|
|
|
$this->prefix = $label . $separator; |
27
|
|
|
$this->startingAt = lengthOf($this->prefix); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Creates a new array limiter that limits input to fields with this prefix. |
32
|
|
|
* |
33
|
|
|
* @param string $label The label to use in the prefix. |
34
|
|
|
* @param string $separator The separator between the label and the field. |
35
|
|
|
* @return FiltersTheArray The prefix limiter. |
36
|
|
|
*/ |
37
|
|
|
public static function with( |
38
|
|
|
string $label, |
39
|
|
|
string $separator = '_' |
40
|
|
|
): FiltersTheArray { |
41
|
|
|
return new self($label, $separator); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** @inheritdoc */ |
45
|
|
|
public function only(array $input): array |
46
|
|
|
{ |
47
|
|
|
return filtered(andMapped([$this, 'filterOutIrrelevantData'], $input)); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** @inheritdoc */ |
51
|
|
|
public function label(): string |
52
|
|
|
{ |
53
|
|
|
return $this->label; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
private function filterOutIrrelevantData(array $row): array |
57
|
|
|
{ |
58
|
|
|
$result = []; |
59
|
|
|
foreach ($row as $column => $value) { |
60
|
|
|
if ($this->isPrefixed($column)) { |
61
|
|
|
$result[$this->withoutPrefix($column)] = $value; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
return $result; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
private function isPrefixed(string $field): bool |
68
|
|
|
{ |
69
|
|
|
return positionOf($field, $this->prefix) === 0; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
private function withoutPrefix(string $field): string |
73
|
|
|
{ |
74
|
|
|
return aPortionOf($field, $this->startingAt); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|