Untitled

 avatar
unknown
plain_text
3 years ago
2.0 kB
6
Indexable
<?php


class Row
{
    private array $values;

    public function __construct(array $values)
    {
        $this->values = $values;
    }
    public function countRow()
    {
        return count($this->values);
    }
}

class Table
{
    private array $rows;
    private Row $header;
    // private Row $row;
    public function __construct(Row $header)
    {
        $this->header = $header;
        // $this->rows[] = $header;
    }

    public function addRow(Row $row): Table
    {
        if ($row->countRow() == $this->header->countRow()) {
            $this->rows[] = $row;
            return $this;
        }
    }

    public function switchRows(int $a, int $b): Table
    {
        $tmp = new Row($this->rows[$a]);
        $this->rows[$a] = $this->rows[$b];
        $this->rows[$b] = $tmp;
        return $this;
    }

    // public function setCellClasses(array $classes): Table
    // {
    //     // TODO
    // }

    // public function setHeaderClasses(array $classes): Table
    // {
    //     // TODO
    // }

    // public function setTableClasses(array $classes): Table
    // {
    //     // TODO
    // }

    public function toHTML(): string
    {
        
        $string = "<table><th>";

        foreach ($this->header as $head) {
            $string .= "<td> $head </td>";
        }
        $string .= "</th><tbody>";
        if(count($this->rows)>0){
             foreach ($this->rows as $row) {
            $string .= "<tr>";
            foreach ($row as $cell) {
                $string .= "<td> $cell </td>";
            }
            $string .= "</tr>";
        }
        $string .= "</tbody></table>";
        }
       
        return $string;
    }
}

$header=new Row(['first_name','last_name','age']);
// var_dump($header);
$table=new Table($header);
$row=new Row(['hame','hamed','20']);
$table->addRow($row);
echo $table->toHTML();
// var_dump($table);
Editor is loading...