Subversion Repositories cheapmusic

Rev

Rev 126 | Blame | Compare with Previous | Last modification | View Log | RSS feed

<?php
/**
 A class that writes html either into a local buffer or directly to the output. Freely distributable as long as this header is kept at the top of the file and not modified.
 @author Jean-Georges Estiot <jgestiot@gmail.com>
 @version 2.0
 */
class Html {
    private $spaces_per_indent;
    private $stack;
    private $attributes;
    private $indent_level;
    private $buffer;
    private $buffered;
    private $newline;

    /**
     init() must be called once before the class is used by the application. It sets up the indent, defaults to buffered output and calls reset().
     @param int $spaces The number of spaces to use in the indentation
     @return void does not return anything
     */

    public function init($spaces = 2) {

        $this->spaces_per_indent = $spaces;
        $this->newline = ($spaces == 0 ? "" : "\n");
        $this->buffered = true;
        $this->reset();
    }

    /**
     Resets some of the key elements of the class: the stack, the indent, the attributes and the buffer.
     @return void does not return anything
     */

    public function reset() {

        $this->stack = array();
        $this->indent_level = 0;
        $this->clear_attributes();
        $this->clear_buffer();
    }

    /**
     * Returns the content of the buffer and clears it
     @return string The content of the buffer.
     */

    public function flush() {

        $temp = $this->buffer;
        $this->clear_buffer();
        return $temp;
    }

    /**
     *clears the buffer
     @return void does not return anything
     */
    private function clear_buffer() {

        $this->buffer = '';
    }

    /**
     Sets the buffering to true or false. If false, the class will output the tags immediately. If true, it will keep all content into the buffer for later use.
     @param bool $how True for buffered and false for unbuffered.
     @return void does not return anything
     */

    public function set_buffered($how) {

        $this->buffered = $how;
    }

    /**
     Writes a string to the buffer. This is the only function in the class that outputs. If $indent is set to true, the string output is correctly indented, relative to other code.
     @param string $string The string to write to output
     @param bool $indent True to indent the string or false otherwise
     @return void does not return anything
     */

    public function write($string, $indent = false) {

        if ($indent) $string = $this->make_indent() . $string;
        if ($this->buffered) {
            $this->buffer .= $string;
        } else {
            echo $string;
        }
    }

    /**
     Adds a single attribute to the next tag.
     Example for an `<input>` tag: add_attribute('type','checkbox');
     @param string $name The name of the attribute
     @param string $value The value of the attribute
     @return void does not return anything
     */

    public function add_attribute($name, $value) {

        $this->attributes[$name] = $value;
    }

    /**
     Adds more than one attribute to the next tag
     The attributes for the tag are passed in the format array('attribute'=>'value').
     So array('id'=>'tag_id','class'=>'myclass') would produce this div tag:
     `<div id="tag_id" class="myclass">`
     @param array $ar The array holding the attributes
     @return void does not return anything
     */

    public function add_attributes($ar) {

        if (is_array($ar)) {

            $this->attributes = array_merge($this->attributes, $ar);
        }
    }

    /**
     Outputs the attributes for the tag that were added with add_attribute() or add_attributes().
     Example: if the previously-added attributes are array('id'=>'tag_id','class'=>'myclass'),  expand_attributes() will
     produce the string 'id="tag_id" class="myclass'.
     Important: all attributes are cleared once the string is output.
     @return void does not return anything
     */

    private function expand_attributes() {

        foreach ($this->attributes as $idx => $val) {
            $this->write(' ' . strtolower($idx) . '=' . '"' . $val . '"');
        }

        $this->clear_attributes(); //always clear attributes when finished
    }

    /**
     Clears all attributes. (The next tag will have no attributes)
     @return void does not return anything
     */

    public function clear_attributes() {

        $this->attributes = array();
    }

    /**
     Generates a tag. There are three flavours:
     1) Open tags with no close and no content. Just the attributes if required: `<div class="myclass">`. This tag will require a call to close()
     2) Tags that never require a close such as `<img href="image.jpg" />`
     3) Tags that have content and are immediately terminated on the same line `<h1>Hello</h1>`
     For the first, use tag('div');
     For the second, use tag('img',false,false) or the function single_tag()
     For the third, simply pass the tag's content like so: tag('h1','Hello')
     @param string $tag The name of the tag. For example 'div' for the `<div>` tag
     @param mixed $content A string for tags such as `<h1>string</h1>`
     @param bool $push A flag indicating if the tag should be pushed onto the stack
     @return void does not return anything
     */

    public function tag($tag, $content = null, $push = true) {
        $has_content = !is_null($content) && $content !== false; // the content can be an empty string
        $has_single_tag = $content === false;

        if ($push) {
            array_push($this->stack, $tag);
        }

        $this->indent();
        $this->write('<' . strtolower($tag));
        $this->expand_attributes();
        if ($has_single_tag) $this->write(" /");
        $this->write('>');

        if ($push) $this->indent_level++;

        if ($has_content) $this->write($content);

        if (!$has_content) $this->write($this->newline);

        if ($push && $has_content) {
            $this->close(false);
        }
    }

    /**
     Outputs a single tag such as `<img />` or `<input />`. Single tags do not require a closing tag.
     @param string $tag The name of the tag. For example 'input' for an `<input />` tag
     @return void does not return anything
     */

    public function single_tag($tag) {

        $this->tag($tag, false, false);
    }

    /**
     Closes the last opened tag. if $indent is set to false, there is no indentation, which is useful for tags
     where the open and close are on the same line like `<h1>Title</h1>`
     @param bool $indent A flag controlling the indent. True for using indent
     @return void does not return anything
     */

    public function close($indent = true) {

        $tag = array_pop($this->stack);

        $this->indent_level--;
        if ($indent) $this->indent();
        $this->write('</' . $tag . ">" . $this->newline);
    }

    /**
     Returns the padding needed to indent a tag or string of text
     @return void does not return anything
     */

    private function make_indent() {

        return str_repeat(' ', $this->indent_level * $this->spaces_per_indent);
    }

    /**
     * Performs the indentation by writing the padding returned by make_indent() to the output.
     @return void does not return anything
     */

    private function indent() {

        if ($this->indent_level > 0) $this->write($this->make_indent());
    }

    /**
     Appends some arbitrary code to the buffer or ouputs it after applying the current indent level before the code and each time a newline is found.
     If properly indented code is passed, it will be appended and properly indented into the existing html code.
     A newline is inserted after the code. To avoid double newlines, a trailing newlines are removed from $code before any processing happens.
     @param string $code The code to be appended
     @return void does not return anything
     */

    public function insert_code($code) {

        $code = preg_replace('/\n$/','', $code);
        $indent_factor = $this->newline . $this->make_indent();

        $this->indent();
        $code = str_replace("\n", $indent_factor, $code);

        $this->write($code . $this->newline);
    }

    /**
     Shortcut function to write a `<br>` to the buffer
     @param bool $indent A flag controlling the indent. True for using indent
     @return void does not return anything
     */

    public function br($indent = false) {

        $this->write('<br>', $indent);
    }

    /**
     Shortcut function to write a newline `\n` to the buffer
     @return void does not return anything
     */

    public function nl() {

        $this->write($this->newline);
    }

    /**
     Shortcut function to write both `<br>` and `\n` to the buffer
     @param bool $indent A flag controlling the indent. True for using indent
     @return void does not return anything
     */

    public function brnl($indent = true) {

        $this->br($indent);
        $this->nl();
    }

} // Ends html Class