public function order($order, $context)
{
if (!$order) {
return null;
}
$model = $context->model();
$alias = $context->alias();
$normalized = array();
if (is_string($order)) {
if (preg_match('/^(.*?)\\s+((?:A|DE)SC)$/i', $order, $match)) {
$normalized[$match[1]] = strtoupper($match[2]);
} else {
$normalized[$order] = 'ASC';
}
} else {
foreach ($order as $field => $direction) {
if (is_int($field)) {
$normalized[$direction] = 'ASC';
} elseif (in_array($direction, array('ASC', 'DESC', 'asc', 'desc'))) {
$normalized[$field] = strtoupper($direction);
} else {
$normalized[$field] = 'ASC';
}
}
}
$escaped = array();
foreach ($normalized as $field => $direction) {
if (!$model || !$model::schema($field)) {
$field = $this->name($field);
} else {
$field = $this->name($alias) . '.' . $this->name($field);
}
$escaped[] = "{$field} {$direction}";
}
return 'ORDER BY ' . join(', ', $escaped);
}