1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of plumphp/plum. |
5
|
|
|
* |
6
|
|
|
* (c) Florian Eckerstorfer <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
namespace Plum\Plum\Converter; |
12
|
|
|
|
13
|
|
|
use Cocur\Vale\Vale; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* MappingConverter. |
17
|
|
|
* |
18
|
|
|
* @author Florian Eckerstorfer <[email protected]> |
19
|
|
|
* @copyright 2014-2016 Florian Eckerstorfer |
20
|
|
|
*/ |
21
|
|
|
class MappingConverter implements ConverterInterface |
22
|
|
|
{ |
23
|
|
|
/** |
24
|
|
|
* @var array |
25
|
|
|
*/ |
26
|
|
|
protected $mappings; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param array $mappings |
30
|
|
|
* |
31
|
|
|
* @codeCoverageIgnore |
32
|
|
|
*/ |
33
|
|
|
public function __construct(array $mappings = []) |
34
|
|
|
{ |
35
|
|
|
foreach ($mappings as $mapping) { |
36
|
|
|
$this->addMapping( |
37
|
|
|
$mapping['from'], |
38
|
|
|
$mapping['to'], |
39
|
|
|
isset($mapping['remove']) ? $mapping['remove'] : true |
40
|
|
|
); |
41
|
|
|
} |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @param string|array $from |
46
|
|
|
* @param string|array $to |
47
|
|
|
* @param bool $remove |
48
|
|
|
* |
49
|
|
|
* @return MappingConverter |
50
|
|
|
*/ |
51
|
3 |
|
public function addMapping($from, $to, $remove = true) |
52
|
|
|
{ |
53
|
3 |
|
$this->mappings[] = ['from' => $from, 'to' => $to, 'remove' => $remove]; |
54
|
|
|
|
55
|
3 |
|
return $this; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @param mixed $item |
60
|
|
|
* |
61
|
|
|
* @return mixed |
62
|
|
|
*/ |
63
|
6 |
|
public function convert($item) |
64
|
|
|
{ |
65
|
6 |
|
foreach ($this->mappings as $mapping) { |
66
|
6 |
|
if (!empty($mapping['from']) && !empty($mapping['to'])) { |
67
|
3 |
|
$item = Vale::set($item, $mapping['to'], Vale::get($item, $mapping['from'])); |
68
|
3 |
|
if ($mapping['remove']) { |
69
|
2 |
|
$item = Vale::remove($item, $mapping['from']); |
70
|
2 |
|
} |
71
|
6 |
|
} elseif (!empty($mapping['to'])) { |
72
|
1 |
|
$item = Vale::set([], $mapping['to'], $item); |
73
|
3 |
|
} elseif (!empty($mapping['from'])) { |
74
|
1 |
|
$item = Vale::get($item, $mapping['from']); |
75
|
1 |
|
} |
76
|
6 |
|
} |
77
|
|
|
|
78
|
6 |
|
return $item; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|