I'm attempting to create a new mapping for a calculated field of two existing mappings. Something like:
'(space/total_space)' => [
'key' => 'Disk_Free_Percentage',
],
Where 'space' is divided by 'total_space' to get a percentage. The code I am using this far is below and I am stuck on this last piece. Any help or pointers would be greatly appreciated.
// Call API to get servers
$rawData = $admin->servers();
// Data mapping
$map = [
'server_name' => [
'key' => 'Node',
],
'space' => [
'key' => 'Disk_Free_GB',
],
'total_space' => [
'key' => 'Total_Disk_GB',
],
'ram' => [
'key' => 'Free_RAM_GB',
'normalize' => function ($data) {
return number_format($data / 1024, 2);
},
],
'total_ram' => [
'key' => 'Total_RAM_GB',
'normalize' => function ($data) {
return number_format($data / 1024, 2);
},
],
'numvps' => [
'key' => 'VMs',
],
'version' => [
'key' => 'Version',
],
];
// Remap data
$data = [];
foreach ($rawData['servs'] as $row) {
$item = [];
foreach ($map as $fieldName => $field) {
// Validate key exists
if (!isset($field['key'])) {
throw new LogicException(sprintf('Field %s must supply a key', $fieldName));
}
// Get data from API
if (isset($row[$fieldName])) {
$value = $row[$fieldName];
} else {
// Use null if data not given by API
$value = null;
}
// Run normalize where set
if (isset($field['normalize']) && is_callable($field['normalize'])) {
$value = call_user_func($field['normalize'], $value);
}
// Map to new data
$item[$field['key']] = $value;
}
$data[] = $item;
}
// encode JSON
$json = json_encode($data)