1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Ddeboer\DataImport\Step; |
4
|
|
|
|
5
|
|
|
use Ddeboer\DataImport\Exception\MappingException; |
6
|
|
|
use Ddeboer\DataImport\Step; |
7
|
|
|
use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException; |
8
|
|
|
use Symfony\Component\PropertyAccess\Exception\UnexpectedTypeException; |
9
|
|
|
use Symfony\Component\PropertyAccess\PropertyAccessor; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* @author Markus Bachmann <[email protected]> |
13
|
|
|
*/ |
14
|
|
|
class MappingStep implements Step |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @var array |
18
|
|
|
*/ |
19
|
|
|
private $mappings = []; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var PropertyAccessor |
23
|
|
|
*/ |
24
|
|
|
private $accessor; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @param array $mappings |
28
|
|
|
* @param PropertyAccessor $accessor |
29
|
|
|
*/ |
30
|
2 |
|
public function __construct(array $mappings = [], PropertyAccessor $accessor = null) |
31
|
|
|
{ |
32
|
2 |
|
$this->mappings = $mappings; |
33
|
2 |
|
$this->accessor = $accessor ?: new PropertyAccessor(); |
34
|
2 |
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* @param string $from |
38
|
|
|
* @param string $to |
39
|
|
|
* |
40
|
|
|
* @return $this |
41
|
|
|
*/ |
42
|
2 |
|
public function map($from, $to) |
43
|
|
|
{ |
44
|
2 |
|
$this->mappings[$from] = $to; |
45
|
|
|
|
46
|
2 |
|
return $this; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* {@inheritdoc} |
51
|
|
|
* |
52
|
|
|
* @throws MappingException |
53
|
|
|
*/ |
54
|
2 |
|
public function process(&$item) |
55
|
1 |
|
{ |
56
|
|
|
try { |
57
|
2 |
|
foreach ($this->mappings as $from => $to) { |
58
|
2 |
|
$value = $this->accessor->getValue($item, $from); |
59
|
2 |
|
$this->accessor->setValue($item, $to, $value); |
60
|
|
|
|
61
|
2 |
|
$from = str_replace(['[',']'], '', $from); |
62
|
|
|
|
63
|
|
|
// Check if $item is an array, because properties can't be unset. |
64
|
|
|
// So we don't call unset for objects to prevent side affects. |
65
|
2 |
|
if (is_array($item) && isset($item[$from])) { |
66
|
2 |
|
unset($item[$from]); |
67
|
2 |
|
} |
68
|
2 |
|
} |
69
|
2 |
|
} catch (NoSuchPropertyException $exception) { |
70
|
|
|
throw new MappingException('Unable to map item', null, $exception); |
71
|
|
|
} catch (UnexpectedTypeException $exception) { |
72
|
|
|
throw new MappingException('Unable to map item', null, $exception); |
73
|
|
|
} |
74
|
2 |
|
} |
75
|
|
|
} |
76
|
|
|
|