Skip to content

Instantly share code, notes, and snippets.

@tikitikipoo
Created August 1, 2015 02:54
Show Gist options
  • Save tikitikipoo/0bd22cf3035e9703b706 to your computer and use it in GitHub Desktop.
Save tikitikipoo/0bd22cf3035e9703b706 to your computer and use it in GitHub Desktop.
//ひどいソースをリファクタリングしたぜよ
//beofre
/**
* 3階層までならマッピング対応
*
*/
public function recordsToParam($records, $map = null)
{
if (is_object($records)) {
$records = $records->toArray();
}
if (is_null($map)) {
$map = $this->map;
}
$result = [];
foreach ($map as $key => $path) { // map
if (is_array($path)) {
$arr = Hash::get($records, $key);
if (is_object($arr)) {
$arr = $arr->toArray();
}
$_result = [];
if (!empty($arr)) {
if (!isset($arr[0])) {
// $_result[$arr_k][$_key] = Hash::get($arr_v, $_path);
} else {
foreach ($arr as $arr_k => $arr_v) { // value
if (is_object($arr_v)) {
$arr_v = $arr_v->toArray();
}
foreach ($path as $_key => $_path) { // map
if (is_array($_path)) {
$__result = [];
foreach ($_path as $__key => $__path) { // map
$_arr = Hash::get($arr_v, $_key . '.' . $__key);
foreach ($_arr as $_arr_k => $_arr_v) { // value
foreach ($__path as $___key => $___path) { // map
$__result[$_arr_k][$___key] = Hash::get($_arr_v, $___path);
}
}
$_result[$arr_k][$__key] = $__result;
}
} else {
$_result[$arr_k][$_key] = Hash::get($arr_v, $_path);
}
}
}
}
}
$result[$key] = $_result;
} else {
$result[$key] = Hash::get($records, $path);
}
}
return $result;
}
// after
public function recordsToParam($records, $map = null)
{
if (!$records) {
return;
}
if (is_object($records)) {
$records = $records->toArray();
}
if (is_null($map)) {
$map = $this->map;
}
$result = [];
foreach ($map as $k => $path) {
if (is_array($path)) {
$_records = Hash::get($records, $k);
if ($_records) {
if (is_object($_records)) {
$_records = $_records->toArray();
}
if (isset($_records[0])) {
foreach ($_records as $__records) {
if (($pos = strpos($k, '.')) !== false) {
$_k = substr($k, $pos + 1);
$result[$_k][] = $this->recordsToParam($__records, $path);
} else {
$result[$k][] = $this->recordsToParam($__records, $path);
}
}
} else {
$result[$k] = $this->recordsToParam($_records, $path);
}
}
} else {
$result[$k] = Hash::get($records, $path);
}
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment