/**
* Return fields of mapper object as an associative array
* @return array
* @param bool|Cortex $obj
* @param bool|int $rel_depths depths to resolve relations
*/
public function cast($obj = NULL, $rel_depths = 1)
{
$fields = $this->mapper->cast($obj ? $obj->mapper : null);
if (!empty($this->vFields)) {
foreach (array_keys($this->vFields) as $key) {
$fields[$key] = $this->get($key);
}
}
if (is_int($rel_depths)) {
$rel_depths--;
}
if (!empty($this->fieldConf)) {
$fields += array_fill_keys(array_keys($this->fieldConf), NULL);
if ($this->whitelist) {
$fields = array_intersect_key($fields, array_flip($this->whitelist));
}
$mp = $obj ?: $this;
foreach ($fields as $key => &$val) {
// post process configured fields
if (isset($this->fieldConf[$key]) && is_array($this->fieldConf[$key])) {
// handle relations
if (($rel_depths === TRUE || is_int($rel_depths) && $rel_depths >= 0) && ($type = preg_grep('/[belongs|has]-(to-)*[one|many]/', array_keys($this->fieldConf[$key])))) {
$relType = $type[0];
// cast relations
$val = ($relType == 'belongs-to-one' || $relType == 'belongs-to-many') && !$mp->exists($key) ? NULL : $mp->get($key);
if ($val instanceof Cortex) {
$val = $val->cast(null, $rel_depths);
} elseif ($val instanceof CortexCollection) {
$val = $val->castAll($rel_depths);
}
} elseif (isset($this->fieldConf[$key]['type'])) {
if ($this->dbsType == 'sql') {
if ($this->fieldConf[$key]['type'] == self::DT_SERIALIZED) {
$val = unserialize($this->mapper->{$key});
} elseif ($this->fieldConf[$key]['type'] == self::DT_JSON) {
$val = json_decode($this->mapper->{$key}, true);
}
}
if ($this->exists($key) && preg_match('/BOOL/i', $this->fieldConf[$key]['type'])) {
$val = (bool) $this->mapper->{$key};
}
}
}
if ($this->dbsType == 'mongo' && $key == '_id') {
$val = (string) $val;
}
if ($this->dbsType == 'sql' && $key == 'id' && $this->standardiseID) {
$fields['_id'] = $val;
unset($fields[$key]);
}
unset($val);
}
}
// custom getter
foreach ($fields as $key => &$val) {
$val = $this->emit('get_' . $key, $val);
unset($val);
}
return $fields;
}