<?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
*/

/**
* Merges the current template with a wrapper template, the current
* template being inserted into the wrapper at the point where the
* wrap tag exists.
* @tag wact:wrap
* @attributes file insertat replaceat
* @end_tag ENDTAG_REQUIRED
*/
class Wact_Template_Tag_wact_wrap extends Wact_Template_Compiler_Node_View {

    /**
    * The view class corresponding to this template node.
    * @var string
    */
    public $parentViewClass = 'Wact_View_Partial';

    /**
     * @param Wact_Template_Compiler_Parser_TreeBuilder $treeBuilder
     * @return Wact_Template_Compiler_Node::REQUIRE_PARSING
     */
    public function preParse($treeBuilder) {
        // make sure we have all the required attributes
        $file = $this->getAttributeValue('file');
        if (empty($file)) {
            throw new Wact_Template_Compiler_Exception_Missingattribute(
                'file', $this->tag, $this->sourceLocation->file, $this->sourceLocation->line);
        }

        // read resource
        $data = $treeBuilder->getCompilingContext()->readSource($file);
        if (!$data) {
            throw new Wact_Template_Compiler_Exception('Cannot read resource "{ResourceId}"', $file);
        }

        // parse the file
        $treeBuilder->parseSource($data, $this, $file);

        // insert or replace?
        $insertionId = $this->getAttributeValue('insertat');
        if ($insertionId) {
            $replace = false;
        } else {
            $insertionId = $this->getAttributeValue('replaceat');
            if (empty($insertionId)) {
                throw new Wact_Template_Compiler_Exception_Missingattribute(
                    'insertat or replaceat', $this->tag, $this->sourceLocation->file, $this->sourceLocation->line);
            }
            $replace = true;
        }

        // Get the insertion point component
        $insertionPoint = $this->findChild($insertionId);
        if (empty($insertionPoint)) {
            throw new Wact_Template_Compiler_Exception('Wrap insertion point "{InsertionPoint}" not found', $insertionId);
        }

        if ($replace) {
            $insertionPoint->removeChildren();
        }

        // The xml under the current component will be built at insertionPoint
        $treeBuilder->setCursor($insertionPoint);

        return parent::REQUIRE_PARSING;
    }
}
?>