Skip to content

Instantly share code, notes, and snippets.

@htfy96
Created July 12, 2016 15:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save htfy96/4fae21a621b0e44d42892c8119a45bd7 to your computer and use it in GitHub Desktop.
Save htfy96/4fae21a621b0e44d42892c8119a45bd7 to your computer and use it in GitHub Desktop.
Bidirectional mapping model in PHP
<?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