template = $template; } } /** * Sets a partial document * * @param string $partial A path to the partial document * @param string $target The target XPath */ public function setPartial($partial, $target) { if (is_file($partial) && !empty($target)) { $this->partials[$partial] = $target; } } /** * Removes a partial document * * @param string $partial */ public function unsetPartial($partial) { if (array_key_exists($partial, $this->partials)) { unset($this->partials[$partial]); } } /** * Returns a file which has been parsed by PHP * * @param string $file The path and file name of the file to parse * @return string The parsed file */ protected function parse($file) { $out = ''; if (is_file($file)) { ob_start(); include $file; $out = ob_get_contents(); ob_end_clean(); } return $out; } /** * Loads a partial into the template * * @param string $source The path and file name to the partial * @param string $target The target XPath to place the partial in */ protected function load($source, $target) { $xpath = new DOMXPath($this->document); $items = $xpath->query($target); if ($items->length > 0) { $source = $this->parse($source); $fragment = $this->document->createDocumentFragment(); $fragment->appendXML($source); $items->item(0)->appendChild($fragment); } } /** * Renders the HTML document * */ public function render() { if (empty($this->template) || !is_array($this->partials)) { throw new Exception('Unable to render: incomplete view configuration.'); } $templateContents = $this->parse($this->template); if (!empty($templateContents)) { $this->document = new DOMDocument; $this->document->loadHTML($templateContents); foreach ($this->partials as $source => $target) { $this->load($source, $target); } return $this->output($this->document->saveHTML()); } } }