add row at json view table

This commit is contained in:
Kavalar 2024-11-28 11:57:17 +03:00
parent 5f46431d45
commit 5effacf12f
2 changed files with 62 additions and 17 deletions

View File

@ -7,6 +7,10 @@ use Itguild\Tables\ViewJsonTable;
$json = file_get_contents('view.json');
$table = new ViewJsonTable($json);
$table->addRow("Имя", function (){
return "Kirill";
}, ['after' => 'username']);
//$table->rows([
$table->rows([
'username' => function ($cell) {

View File

@ -11,6 +11,9 @@ class ViewJsonTable extends JasonTable
private array $data;
private string $json;
private array $dataJson;
private array $customRowsArray = [];
public function __construct($json)
{
$this->beforePrintCell = [];
@ -35,31 +38,27 @@ class ViewJsonTable extends JasonTable
$this->html .= "<table $paramsStr>";
}
public function createRows(): string
{
foreach ($this->data['meta']['rows'] as $key => $row) {
if ($this->issetRow($key)) {
$rowsBefore = $this->getCustomRows($key, "before");
$rowsAfter = $this->getCustomRows($key, "after");
if ($this->beforePrintCell) {
$this->dataJson[$key] = $this->getCustomCell($key, $this->dataJson[$key]);
}
foreach ($rowsBefore as $item){
$this->html .= "<tr><th>" . $item['label'] . "</th><td>" . $this->getCustomRowHandler($item) . "</td></tr>";
}
$this->html .= "<tr><th>" . $row . "</th><td>" . $this->dataJson[$key] . "</td></tr>";
foreach ($rowsAfter as $item){
$this->html .= "<tr><th>" . $item['label'] . "</th><td>" . $this->getCustomRowHandler($item) . "</td></tr>";
}
}
}
return $this->html;
}
private function issetRow($column): bool
{
if (isset($this->data['meta']['rows'])){
foreach ($this->data['meta']['rows'] as $key => $currentColumn){
if ($key === $column){
return true;
}
}
}
return false;
}
public function endTable(): void
{
@ -85,4 +84,46 @@ class ViewJsonTable extends JasonTable
$this->beforePrintCell[$key] = $value;
}
}
public function addRow(string $label, \Closure $handler, array $position = []): void
{
$this->customRowsArray[] = ['label' => $label, 'handler' => $handler, 'position' => $position];
}
private function issetRow($column): bool
{
if (isset($this->data['meta']['rows'])) {
foreach ($this->data['meta']['rows'] as $key => $currentColumn) {
if ($key === $column) {
return true;
}
}
}
return false;
}
private function getCustomRows(string $key, string $position): array
{
$customRows = [];
foreach ($this->customRowsArray as $item) {
if (!empty($item['position'])) {
if (isset($item['position'][$position]) && $item['position'][$position] === $key){
$customRows[] = $item;
}
}
}
return $customRows;
}
private function getCustomRowHandler(array $row): mixed
{
if (isset($row['handler'])){
return $row['handler']();
}
return false;
}
}