Files
ulmus/src/Query/Values.php
T

70 lines
1.7 KiB
PHP

<?php
namespace Ulmus\Query;
use Ulmus\QueryBuilder\QueryBuilderInterface;
class Values extends Fragment {
public int $order = 0;
public ? int $fieldCount = null;
public array $rows = [];
public QueryBuilderInterface $queryBuilder;
public function __construct(QueryBuilderInterface $queryBuilder)
{
$this->queryBuilder = $queryBuilder;
}
public function add(array $row) : self
{
if ($row === []) {
return $this;
}
if ($this->fieldCount === null) {
$this->fieldCount = count($row);
}
# index starts at '1' for Pdo params
$this->rows[] = array_combine(range(1, count($row)), array_values($row));
return $this;
}
public function render() : string
{
$this->queryBuilder->addValues($this->flattenRowsArray());
return $this->renderSegments([
'VALUES', $this->renderParameterPlaceholders(),
]);
}
public function renderParameterPlaceholders() : string
{
$return = [];
foreach($this->rows as $row) {
if ($this->fieldCount === null) {
}
else {
if (count($row) !== $this->fieldCount) {
throw new \Exception("Insert statement must contains the same number of values for each rows.");
}
}
$return[] = implode(',', array_fill(0, $this->fieldCount, '?'));
}
return "(" . implode('),(', $return) . ")";
}
public function flattenRowsArray() : array
{
return \iterator_to_array(new \RecursiveIteratorIterator(new \RecursiveArrayIterator($this->rows)));
}
}