Passed
Push — master ( d74703...28a6a0 )
by Roman
02:05
created

Table::setData()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
4
namespace ToolkitLab\ASCII;
5
6
7
class Table
8
{
9
    private $data = [];
10
    private $dimensionX;
11
    private $dimensionY;
12
    private $columnsMaxLenght = [];
13
14 28
    public function __construct($_data, $_dimensionX = null, $_dimensionY = null)
15
    {
16 28
        $this->data = $_data;
17 28
        if (is_null($_dimensionX)) {
18 28
            $this->calculateDimensions();
19 28
        } else {
20
            $this->dimensionX = $_dimensionX;
21
            $this->dimensionY = $_dimensionY;
22
        }
23 28
    }
24
25 26
    public function getCell($x, $y)
26
    {
27 26
        if ($x >= $this->dimensionX || $y >= $this->dimensionY) {
28
            throw new \Exception("Index Out of range");
29
        }
30 26
        if (!isset($this->data[$y][$x])) {
31
            return "";
32
        }
33 26
        return $this->data[$y][$x];
34
    }
35
36
    /**
37
     * @param int $columnIndex
38
     * @return int
39
     */
40 22
    public function getColumnsMaxLenght($columnIndex)
41
    {
42 22
        if(isset($this->columnsMaxLenght[$columnIndex])) return $this->columnsMaxLenght[$columnIndex];
43 22
        $width = 0;
44 22
        for ($y = 0; $y < $this->dimensionY; $y++) {
45 22
            $len = strlen($this->getCell($columnIndex, $y));
46 22
            if ($len > $width) $width = $len;
47 22
        }
48
49 22
        $this->columnsMaxLenght[$columnIndex] = $width;
50 22
        return $width;
51
    }
52
53
    /**
54
     * @return array
55
     */
56
    public function getData()
57
    {
58
        return $this->data;
59
    }
60
61 28
    private function calculateDimensions()
62
    {
63 28
        $this->dimensionY = $this->dimensionX = 0;
64
65 28
        foreach ($this->data as $row) {
66 28
            $cnt = count($row);
67 28
            if ($cnt > $this->dimensionX) $this->dimensionX = $cnt;
68 28
        }
69 28
        $this->dimensionY = count($this->data);
70 28
    }
71
72
    /**
73
     * @param array $data
74
     */
75 2
    public function setData($data)
76
    {
77 2
        $this->data = $data;
78 2
        $this->calculateDimensions();
79 2
    }
80
81
    /**
82
     * @return mixed
83
     */
84 24
    public function getDimensionX()
85
    {
86 24
        return $this->dimensionX;
87
    }
88
89
    /**
90
     * @return mixed
91
     */
92 24
    public function getDimensionY()
93
    {
94 24
        return $this->dimensionY;
95
    }
96
}