Table::caption()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 5
rs 10
1
<?php
2
3
4
namespace Riclep\Storyblok\Fields;
5
6
7
use Illuminate\Support\Arr;
8
use Riclep\Storyblok\Field;
9
10
class Table extends Field
11
{
12
	/**
13
	 * @var array|string caption for the table
14
	 */
15
	protected string|array $caption = '';
16
17
	/**
18
	 * @var string a class to apply to the <table> tag
19
	 */
20
	protected string $cssClass = '';
21
22
	/**
23
	 * @var array|int the column numbers to convert to headers
24
	 */
25
	protected array|int $headerColumns = [];
26
27
	protected function toHtml($table): string
28
	{
29
		$html = '<table ' . ($this->cssClass ? 'class="' . $this->cssClass . '"' : null) . '>';
30
31
		if ($this->caption) {
32
			if (is_array($this->caption)) {
33
				$html .= '<caption class="' . $this->caption[1] . '">' . $this->caption[0] . '</caption>';
34
			} else {
35
				$html .= '<caption>' . $this->caption . '</caption>';
36
			}
37
		}
38
39
		$html .= '<thead><tr>';
40
41
		foreach ($table['thead'] as $header) {
42
			$html .= '<th>' . nl2br($header['value']) . '</th>';
43
		}
44
45
		$html .= '</tr></thead><tbody>';
46
47
		foreach ($table['tbody'] as $row) {
48
			$html .= '<tr>';
49
50
			foreach ($row['body'] as $column => $cell) {
51
				if ($this->headerColumns && in_array(($column + 1), Arr::wrap($this->headerColumns))) {
52
					$html .= '<th>' . nl2br($cell['value'])  . '</th>';
53
				} else {
54
					$html .= '<td>' . nl2br($cell['value'])  . '</td>';
55
				}
56
			}
57
58
			$html .= '</tr>';
59
		}
60
61
		return $html . '</tbody></table>';
62
	}
63
64
	public function __toString(): string
65
	{
66
		return $this->toHtml($this->content);
67
	}
68
69
	public function caption($caption): self
70
	{
71
		$this->caption = $caption;
72
73
		return $this;
74
	}
75
76
	public function cssClass($cssClass): self
77
	{
78
		$this->cssClass = $cssClass;
79
80
		return $this;
81
	}
82
}