summaryrefslogtreecommitdiff
path: root/demos/quickstart/protected/controls/TTextHighlighter.php
blob: bc74b5afeb4f79660355698d3c8e53b6524acd13 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php

require_once(dirname(__FILE__).'/Highlighter/geshi.php');

Prado::using('System.IO.TTextWriter');

/**
 * ${classname}
 *
 * ${description}
 *
 * @author Wei Zhuo<weizhuo[at]gmail[dot]com>
 * @version $Revision: 1.66 $  $Date: ${DATE} ${TIME} $
 * @package ${package}
 */
class TTextHighlighter extends TWebControl
{
	/**
	 * @return string tag name of the panel
	 */
	protected function getTagName()
	{
		return 'div';
	}

	public function getLanguage()
	{
		return $this->getViewState('Language', 'php');
	}

	public function setLanguage($value)
	{
		$this->setViewState('Language', $value, 'php');
	}

	public function setEnableLineNumbers($value)
	{
		$this->setViewState('LineNumbers', TPropertyValue::ensureBoolean($value), false);
	}

	public function getEnableLineNumbers()
	{
		return $this->getViewState('LineNumbers', false);
	}

	protected function onPreRender($writer)
	{
		parent::onPreRender($writer);
		$this->registerTextHighlightStyleSheet();
	}

	public function addParsedObject($object)
	{
		if(is_string($object))
			$object=html_entity_decode($object);
		parent::addParsedObject($object);
	}

	protected function renderContents($writer)
	{
		$textWriter=new TTextWriter;
		parent::renderContents(new THtmlWriter($textWriter));
		$writer->write($this->highlightText($textWriter->flush()));
	}

	/**
	 * Register CSS style sheet file.
	 */
	protected function registerTextHighlightStyleSheet()
	{
		$cs = $this->getPage()->getClientScript();
		if(!$cs->isStyleSheetFileRegistered(get_class($this)))
		{
			$styleSheet = $this->getAsset('Highlighter/code_highlight.css');
			$cs->registerStyleSheetFile(get_class($this), $styleSheet);
		}
	}

	/**
	 * Returns the highlighted text.
	 * @param string text to highlight.
	 * @return string highlighted text.
	 */
	protected function highlightText($text)
	{
		$geshi = new GeSHi(trim($text), $this->getLanguage());
		if($this->getEnableLineNumbers())
			$geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS);
		$geshi->enable_classes();
		return $geshi->parse_code();
	}
}
?>