ulmus/src/Query/Select.php

58 lines
1.2 KiB
PHP

<?php
namespace Ulmus\Query;
class Select extends Fragment {
const FIELD_AS = "%s as %s";
public int $order = -100;
public bool $distinct = false;
public bool $union = false;
public bool $isInternalSelect = false;
public ? int $top = null;
protected array $fields = [];
const SQL_TOKEN = "SELECT";
public function set($fields) : self
{
$this->fields = is_array($fields) ? $fields : [ $fields ];
return $this;
}
public function add($fields) : self
{
if ( is_array($fields) ) {
$this->fields = array_merge($this->fields, $fields);
}
else {
$this->fields[] = $fields;
}
return $this;
}
public function render() : string
{
foreach($this->fields as $key => &$value) {
if ( ! is_numeric($key) ) {
$value = sprintf(static::FIELD_AS, $value, $key);
}
}
return $this->renderSegments([
( $this->union ? 'UNION' : false ),
static::SQL_TOKEN,
( $this->distinct ? 'DISTINCT' : false ),
( $this->top ? sprintf('TOP (%s)', $this->top) : false ),
implode(', ', $this->fields)
]);
}
}