Created
July 12, 2016 16:01
-
-
Save htfy96/bbe02bc8858c0b8af1750c22613e01ba to your computer and use it in GitHub Desktop.
Bidirectional mapper of PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
interface iBidirectionTrans { | |
public function forward_map($left_val); | |
public function reverse_map($right_val, &$left_obj); | |
} | |
class KeyMapper implements iBidirectionTrans { | |
private $pos; | |
public function __construct($pos) { | |
$this->pos = $pos; | |
} | |
public function forward_map($left_val) { | |
return $left_val[$this->pos]; | |
} | |
public function reverse_map($right_val, &$left_obj) { | |
$left_obj[$this->pos] = $right_val; | |
} | |
} | |
class ArrayMapper implements iBidirectionTrans { | |
private $arr; | |
public function __construct($arr) { | |
assert(is_array($arr)); | |
$this->arr = $arr; | |
} | |
public function forward_map($left_val) { | |
return array_map(function($mapper) use ($left_val) { | |
if (is_subclass_of($mapper, "iBidirectionTrans")) | |
return $mapper->forward_map($left_val); | |
else | |
return $mapper; | |
}, $this->arr); | |
} | |
public function reverse_map($right_val, &$left_obj) { | |
foreach ($this->arr as $key => $value) { | |
if (!isset($right_val[$key])) | |
error_log("Key $key not found in right"); | |
if (is_subclass_of($value, "iBidirectionTrans")) | |
$value->reverse_map($right_val[$key], $left_obj); | |
else | |
if ($right_val[$key] != $value) | |
error_log("Value of key $key is not satisfied($value expected, ${right_val[$key]} got)"); | |
} | |
} | |
} | |
$__0 = new KeyMapper(0); | |
$__1 = new KeyMapper(1); | |
$__2 = new KeyMapper(2); | |
$model = new ArrayMapper( | |
[ | |
'abc' => $__0, | |
'ccc' => new ArrayMapper( | |
[ | |
'kcd' => 'fdsa', | |
'xxx' => $__1 | |
] | |
) | |
] | |
); | |
$right = $model->forward_map([123, 345]); | |
print_r($right); | |
// Array ( [abc] => 123 [ccc] => Array ( [kcd] => fdsa [xxx] => 345 ) ) | |
$right['abc'] = 789; | |
$right['ccc']['xxx'] = 0; | |
$left = []; | |
$model->reverse_map($right, $left); | |
print_r($left); | |
// Array ( [0] => 789 [1] => 0 ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment