Debian Codegraph @

vendor/ipl/web/src/Style.php

raw
1 <?php
2
3 namespace ipl\Web;
4
5 use ipl\Html\Attribute;
6 use ipl\Html\Attributes;
7 use ipl\Html\BaseHtmlElement;
8 use ipl\Html\HtmlElement;
9 use ipl\Html\HtmlString;
10 use ipl\Html\ValidHtml;
11 use ipl\Web\Less\LessRuleset;
12 use Throwable;
13
14 class Style extends LessRuleset implements ValidHtml
15 {
16 /** @var ?string */
17 protected $module;
18
19 /** @var ?string */
20 protected $nonce;
21
22 /**
23 * Get the used CSP nonce
24 *
25 * @return ?string
26 */
27 public function getNonce(): ?string
28 {
29 return $this->nonce;
30 }
31
32 /**
33 * Set the CSP nonce to use
34 *
35 * @param ?string $nonce
36 *
37 * @return $this
38 */
39 public function setNonce(?string $nonce): self
40 {
41 $this->nonce = $nonce;
42
43 return $this;
44 }
45
46 /**
47 * Get the Icinga module name the ruleset is scoped to
48 *
49 * @return ?string
50 */
51 public function getModule(): ?string
52 {
53 return $this->module;
54 }
55
56 /**
57 * Set the Icinga module name to use as scope for the ruleset
58 *
59 * @param ?string $name
60 *
61 * @return $this
62 */
63 public function setModule(?string $name): self
64 {
65 $this->module = $name;
66
67 return $this;
68 }
69
70 /**
71 * Add CSS properties for the given element
72 *
73 * The created ruleset will be applied by an `#ID` selector. If the given
74 * element does not have an ID set yet, one is automatically set.
75 *
76 * @param BaseHtmlElement $element Element to apply the properties to
77 * @param array<string, string> $properties CSS properties
78 *
79 * @return $this
80 */
81 public function addFor(BaseHtmlElement $element, array $properties): self
82 {
83 /** @var ?string $id */
84 $id = $element->getAttribute('id')->getValue();
85
86 if ($id === null) {
87 $id = uniqid('csp-style', false);
88 $element->setAttribute('id', $id);
89 }
90
91 return $this->add('#' . $id, $properties);
92 }
93
94 public function render(): string
95 {
96 if ($this->module !== null) {
97 $ruleset = (new static())
98 ->setSelector(".icinga-module.module-$this->module")
99 ->addRuleset($this);
100 } else {
101 $ruleset = $this;
102 }
103
104 return (new HtmlElement(
105 'style',
106 (new Attributes())->addAttribute(new Attribute('nonce', $this->getNonce())),
107 HtmlString::create($ruleset->renderCss())
108 ))->render();
109 }
110
111 /**
112 * Render to HTML
113 *
114 * @return string
115 */
116 public function __toString(): string
117 {
118 try {
119 return $this->render();
120 } catch (Throwable $e) {
121 return sprintf('<!-- Failed to render style: %s -->', $e->getMessage());
122 }
123 }
124 }