lithium\data\source\Database::order()

public method

Return formatted clause for ORDER BY with known fields escaped and directions normalized to uppercase. When order direction is missing or unrecognized defaults to ASC.

Parameters

  • string|array $order

    The clause to be formatted.

  • object $context

Returns

string|null

Formatted clause, null if there is nothing to format.

Source

	public function order($order, $context) {
		if (!$order) {
			return null;
		}
		$model = $context->model();
		$alias = $context->alias();

		$normalized = [];
		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, ['ASC', 'DESC', 'asc', 'desc'])) {
					$normalized[$field] = strtoupper($direction);
				} else {
					$normalized[$field] = 'ASC';
				}
			}
		}

		$escaped = [];
		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);
	}