SubTabled::translateData()   B
last analyzed

Complexity

Conditions 9
Paths 15

Size

Total Lines 37
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 23
c 0
b 0
f 0
dl 0
loc 37
rs 8.0555
cc 9
nc 15
nop 0
1
<?php
2
3
namespace kalanis\kw_table\output_kw;
4
5
6
use kalanis\kw_connect\core\ConnectException;
7
use kalanis\kw_table\core\Table;
8
use kalanis\kw_table\core\TableException;
9
10
11
/**
12
 * Class SubTabled
13
 * @package kalanis\kw_table\output_kw
14
 * Allow to render sub-table as row
15
 * This one cannot be rendered in CLI or JSON
16
 */
17
class SubTabled extends Table
18
{
19
    /** @var Table\Rows\TableRow[] */
20
    private array $rowCallback = [];
21
22
    final public function setOutput(Table\AOutput $output): void
23
    {
24
        // cannot be set
25
        $this->output = new KwRenderer($this);
26
    }
27
28
    /**
29
     * Update columns to readable format
30
     * @throws ConnectException
31
     * @throws TableException
32
     */
33
    public function translateData(): void
34
    {
35
        if (is_null($this->dataSetConnector)) {
36
            throw new TableException('Cannot create table from empty dataset');
37
        }
38
39
        if (empty($this->columns)) {
40
            throw new TableException('You need to define at least one column');
41
        }
42
43
        $this->applyFilter();
44
        $this->applyOrder();
45
        $this->applyPager();
46
47
        $this->getDataSetConnector()->fetchData();
48
49
        foreach ($this->getDataSetConnector() as $source) {
50
            $rowData = new Table\Internal\Row();
51
            $rowData->setSource($source);
52
53
            foreach ($this->callRows as $call) {
54
                call_user_func_array([$rowData, $call->getFunctionName()], $call->getFunctionArgs());
55
            }
56
57
            foreach ($this->columns as $column) {
58
                $col = clone $column;
59
                $rowData->addColumn($col);
60
            }
61
62
            $this->tableData[] = $rowData;
63
64
            foreach ($this->rowCallback as $call) {
65
                $callback = call_user_func_array($call->getFunctionName(), array_merge(['rowData' => $rowData], $call->getFunctionArgs()));
66
                if ($callback instanceof Table || $callback instanceof Table\Internal\Row) {
67
                    $this->tableData[] = $callback;
68
                } else {
69
                    throw new TableException('Row callback needs to return \kalanis\kw_table\Table or \kalanis\kw_table\Table\Internal\Row');
70
                }
71
            }
72
        }
73
    }
74
75
    /**
76
     * @param callable $function
77
     * @param string[] $arguments styles
78
     */
79
    protected function addRowCallback($function, array $arguments = []): void
80
    {
81
        $this->rowCallback[] = new Table\Rows\TableRow($function, $arguments);
82
    }
83
}
84