<?php
/**
 * Web Application Component Toolkit
 *
 * @link http://www.phpwact.org/
 *
 * @author Wact Development Team
 * @link http://www.phpwact.org/team
 *
 * @copyright Copyright 2006, Jeff Moore
 * @license http://opensource.org/licenses/mit-license.php MIT
 */

/**
 * A series of exceptions can be collected, encapsulated into a single unit and
 * re-thrown with this class.
 */
class Wact_Exception_Collection extends Wact_Exception_Base {

    /**
     * @var array List of exceptions
     */
    protected $collection;

    /**
     * Class constructor.
     * @param array a list of exceptions
     */
    function __construct() {

        $args = func_get_args();
        if (count($args) > 0) {
            $this->collection = array_shift($args);
        } else {
            $this->collection = array();
        }

        if (count($args) == 0) {
            parent::__construct('{ExceptionCount} exceptions occurred', 
                count($this->collection));
        } else {
            parent::__construct($args);
        }

    }

    /**
     * Returns a list of exceptions
     * @return array A list of Exceptions
     */
    function getCollection() {
        return $this->collection;
    }

    /**
     * Returns a count of the number of exceptions
     * @return int number of exceptions
     */
    function getExceptionCount() {
        return count($this->collection);
    }

    /**
     * An HTML representation of this exception.
     * @return string HTML representation of this exception
     */
    function toHtml($formatter = NULL) {
        if (empty($formatter)) {
            $formatter = new Wact_Exception_Formatter_Html();
        }
    
        $formatter->beginException();

        $formatter->writeExceptionMessage($this->getMessage(),
        $this->getFile(), $this->getLine(), get_class($this));

        $formatter->writeStackTrace($this->getTrace());

        $formatter->beginChildSection("Exceptions");
        $formatter->beginList();
        foreach($this->collection as $e) {
            $formatter->beginListItem();
            $formatter->writeException($e);
            $formatter->endListItem();
        }
        $formatter->endList();
        $formatter->endChildSection();

        $formatter->endException();

        return $formatter->getMessage();
    }

    /**
     * returns the string representation of this exception, including any wrapped
     * exceptions.
     * @return string representation of this exception
     */
    function __toString() {
        $message = parent::__toString();
        foreach($this->collection as $key => $e) {
            $message .= "\nException#{$key}:\n    " .
            str_replace("\n", "\n    ", $e->__toString());
        }
        return $message;
    }

}

?>