|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* inetprocess/transformation |
|
4
|
|
|
* |
|
5
|
|
|
* PHP Version 5.3 |
|
6
|
|
|
* |
|
7
|
|
|
* @author Rémi Sauvat |
|
8
|
|
|
* @copyright 2005-2015 iNet Process |
|
9
|
|
|
* |
|
10
|
|
|
* @package inetprocess/transformation |
|
11
|
|
|
* |
|
12
|
|
|
* @license GNU General Public License v2.0 |
|
13
|
|
|
* |
|
14
|
|
|
* @link http://www.inetprocess.com |
|
15
|
|
|
*/ |
|
16
|
|
|
|
|
17
|
|
|
namespace Inet\Transformation\Rule; |
|
18
|
|
|
|
|
19
|
|
|
use Inet\Transformation\Exception\TransformationException; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* Call a function and send back the result |
|
23
|
|
|
*/ |
|
24
|
|
|
class Map extends AbstractRule |
|
25
|
|
|
{ |
|
26
|
|
|
protected $mapping = array(); |
|
27
|
|
|
/** |
|
28
|
|
|
* Operate the transformation |
|
29
|
|
|
* If input is an array each cell is replaced independently |
|
30
|
|
|
* and an array is returned |
|
31
|
|
|
* |
|
32
|
|
|
* @param mixed $input |
|
33
|
|
|
* @param array $arguments |
|
34
|
|
|
* |
|
35
|
|
|
* @throws Inet\Transformation\Exception\TransformationException |
|
36
|
|
|
* |
|
37
|
|
|
* @return mixed |
|
38
|
|
|
*/ |
|
39
|
8 |
|
public function transform($input, $arguments) |
|
40
|
|
|
{ |
|
41
|
|
|
// I should have two arguments: old format / new format |
|
42
|
8 |
|
if (count($arguments) !== 1) { |
|
43
|
2 |
|
throw new TransformationException( |
|
44
|
|
|
'Rule Map expects exactly 1 argument' |
|
45
|
2 |
|
); |
|
46
|
|
|
} |
|
47
|
6 |
|
$mapping = $arguments[0]; |
|
48
|
6 |
|
if (!is_array($mapping)) { |
|
49
|
1 |
|
throw new TransformationException( |
|
50
|
|
|
'First argument of Map should by an assosiative array' |
|
51
|
1 |
|
); |
|
52
|
|
|
} |
|
53
|
5 |
|
$this->mapping = $mapping; |
|
54
|
|
|
|
|
55
|
5 |
|
if (!is_array($input)) { |
|
56
|
4 |
|
return $this->replace($input); |
|
57
|
|
|
} |
|
58
|
1 |
|
return array_map(array($this, 'replace'), $input); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
/** |
|
62
|
|
|
* @param string $value |
|
63
|
|
|
*/ |
|
64
|
5 |
|
public function replace($value) |
|
65
|
|
|
{ |
|
66
|
|
|
// If not array map and return fast |
|
67
|
5 |
|
if (array_key_exists($value, $this->mapping)) { |
|
68
|
2 |
|
return $this->mapping[$value]; |
|
69
|
|
|
} |
|
70
|
|
|
// Couldn't map so return as is |
|
71
|
4 |
|
return $value; |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|