| 1 |
<?php |
| 2 |
|
| 3 |
namespace Tableberg\Renderer\Text; |
| 4 |
|
| 5 |
class TextRenderer { |
| 6 |
/** |
| 7 |
* @param array<string, mixed>|null $attributes |
| 8 |
* @return string |
| 9 |
*/ |
| 10 |
public function render($attributes) { |
| 11 |
$attrs = TextAttrs::from_array($attributes); |
| 12 |
|
| 13 |
$marginShorthand = $this->sides_shorthand($attrs->styles->margin); |
| 14 |
$paddingShorthand = $this->sides_shorthand($attrs->styles->padding); |
| 15 |
|
| 16 |
$styleValues = []; |
| 17 |
$styleValues[] = 'margin:' . ($marginShorthand !== '' ? $marginShorthand : '0'); |
| 18 |
if ($paddingShorthand !== '') { |
| 19 |
$styleValues[] = 'padding:' . $paddingShorthand; |
| 20 |
} |
| 21 |
|
| 22 |
$styleValues[] = 'text-align:' . $attrs->align->asAttr(); |
| 23 |
|
| 24 |
if ($attrs->styles->textColor->isNotEmpty()) { |
| 25 |
$styleValues[] = 'color:' . $attrs->styles->textColor->asAttr(); |
| 26 |
} |
| 27 |
|
| 28 |
if ($attrs->styles->linkColor->isNotEmpty()) { |
| 29 |
$styleValues[] = '--tableberg-text-link-color:' . $attrs->styles->linkColor->asAttr(); |
| 30 |
} |
| 31 |
|
| 32 |
if ($attrs->styles->backgroundColor->isNotEmpty()) { |
| 33 |
$styleValues[] = 'background-color:' . $attrs->styles->backgroundColor->asAttr(); |
| 34 |
} |
| 35 |
|
| 36 |
if ($attrs->styles->fontSize->isNotEmpty()) { |
| 37 |
$styleValues[] = 'font-size:' . $attrs->styles->fontSize->asAttr(); |
| 38 |
} |
| 39 |
|
| 40 |
$styleAttr = implode(';', $styleValues); |
| 41 |
|
| 42 |
return |
| 43 |
"<p class='tableberg-text-element' style='{$styleAttr}'> |
| 44 |
{$attrs->content->asHtml()} |
| 45 |
</p>"; |
| 46 |
} |
| 47 |
|
| 48 |
/** |
| 49 |
* Build a CSS shorthand from a 4-side value; returns '' when all sides |
| 50 |
* are empty so the property can be skipped. |
| 51 |
* |
| 52 |
* @param Sides $sides |
| 53 |
* @return string |
| 54 |
*/ |
| 55 |
private function sides_shorthand($sides) { |
| 56 |
$top = $sides->top->isNotEmpty() ? $sides->top->asAttr() : '0'; |
| 57 |
$right = $sides->right->isNotEmpty() ? $sides->right->asAttr() : '0'; |
| 58 |
$bottom = $sides->bottom->isNotEmpty() ? $sides->bottom->asAttr() : '0'; |
| 59 |
$left = $sides->left->isNotEmpty() ? $sides->left->asAttr() : '0'; |
| 60 |
|
| 61 |
if ($top === '0' && $right === '0' && $bottom === '0' && $left === '0') { |
| 62 |
return ''; |
| 63 |
} |
| 64 |
|
| 65 |
return "{$top} {$right} {$bottom} {$left}"; |
| 66 |
} |
| 67 |
} |
| 68 |
|