From: Andrey Kutejko Date: Thu, 28 Nov 2013 19:34:42 +0000 (+0200) Subject: simple html builder X-Git-Tag: 0.1~8 X-Git-Url: https://git.andy128k.dev/?a=commitdiff_plain;h=cb570caf706719a6fd249a45262e6157b88fcaba;p=missing-tools.git simple html builder --- diff --git a/src/htmlbuilder.php b/src/htmlbuilder.php new file mode 100644 index 0000000..9286c95 --- /dev/null +++ b/src/htmlbuilder.php @@ -0,0 +1,98 @@ +name = $name; + $this->attributes = (array)$attributes; + $this->inner = (array)$inner; + $this->selfClose = in_array($name, array("base", "basefont", "br", "col", "frame", "hr", "input", "link", "meta", "param")); + } + + public static function __callStatic($method, $args) + { + $attributes = array_shift($args); + $inner = array_shift($args); + return new Tag($method, $attributes, $inner); + } + + public function attr($name, $value) + { + $this->attributes[$name] = $value; + } + + public function unsetAttr($name) + { + unset($this->attributes[$name]); + } + + private function getListAttribute($name) + { + $classes = isset($this->attributes[$name]) ? $this->attributes[$name] : array(); + if (!is_array($classes)) + $classes = explode(' ', $classes); + return $classes; + } + + public function addClass($class) + { + $classes = $this->getListAttribute('class'); + if (!in_array($class, $classes)) + $classes[] = $class; + $this->attributes['class'] = $classes; + } + + public function removeClass($class) + { + $classes = $this->getListAttribute('class'); + $k = array_search($class, $classes); + if ($k !== false) + unset($classes[$k]); + $this->attributes['class'] = $classes; + } + + public function append($item) + { + if ($item instanceof Tag) + $this->inner[] = $item; + else + $this->inner[] = htmlspecialchars($item, ENT_COMPAT, 'UTF-8'); + return $this; + } + + public function raw($raw) + { + $this->inner[] = $raw; + return $this; + } + + public function html() + { + $s = '<'.$this->name; + foreach ($this->attributes as $k => $v) { + if (is_array($v)) + $v = implode(' ', $v); + $s .= ' '.$k.'="'.htmlspecialchars($v, ENT_COMPAT, 'UTF-8').'"'; + } + $s .= '>'; + + if (!$this->selfClose) { + foreach ($this->inner as $item) + $s .= (string)$item; + $s .= 'name.'>'; + } + + return $s; + } + + public function __toString() + { + return $this->html(); + } +} + diff --git a/t/HtmlBuilderTest.php b/t/HtmlBuilderTest.php new file mode 100644 index 0000000..3892193 --- /dev/null +++ b/t/HtmlBuilderTest.php @@ -0,0 +1,14 @@ + 'container')) + ->append('Hello, "World"') + ->append(HtmlBuilder\Tag::a()->append('click ')->raw('me')); + + $this->assertEquals('
Hello, "World"click me
', (string)$tag); + } +} +