Skip to content

Instantly share code, notes, and snippets.

@satlavida
Forked from alganet/h.php
Created September 1, 2011 12:59
Show Gist options
  • Save satlavida/1186114 to your computer and use it in GitHub Desktop.
Save satlavida/1186114 to your computer and use it in GitHub Desktop.
HTML generator prototype
<?php
print
h::html(
h::head(
h::title('Hi!')
),
h::body(
h::h1('Hello')->id('oi'),
h::ul(
h::li('foo'),
h::li('bar'),
h::li('baz')
),
h::input()->type('text')->name('username')->value('')
)
);
/* Output Sample:
<html>
<head>
<title>Hi!</title>
</head>
<body>
<h1 id="oi">Hello</h1>
<ul>
<li>foo</li>
<li>bar</li>
<li>baz</li>
</ul>
<input type="text" name="username" value="" />
</body>
</html>
*/
class h {
protected static $indent = 0;
protected $nodeName = '';
protected $childrenNodes = array();
protected $attributes = array();
public static function __callStatic($name, array $children)
{
return new static($name, $children);
}
public function __construct($name, array $children)
{
$this->nodeName = $name;
$this->childrenNodes = $children;
}
public function __call($attribute, $value)
{
$this->attributes[$attribute] = $value[0];
return $this;
}
public function __toString()
{
$children = $this->renderChildren();
$attrs = $this->renderAttributes();
return count($this->childrenNodes)
? "<{$this->nodeName}{$attrs}>$children</{$this->nodeName}>"
: "<{$this->nodeName}{$attrs} />";
}
protected function renderChildren()
{
$d = &static::$indent;
$rendered = implode(array_map(function($child) use (&$d) {
return is_scalar($child)
? $child
: "\n" . str_repeat(' ', ++$d * 2) . $child .
"\n" . str_repeat(' ', --$d * 2);
}, $this->childrenNodes));
return $rendered;
}
protected function renderAttributes()
{
$attrs = '';
foreach ($this->attributes as $attr => &$value)
$attrs .= " $attr=\"$value\"";
return $attrs;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment