Working on a class for code highlighting, mostly for fun
Not done, started today So comment it as it is now
Not done, started today So comment it as it is now
PHP:
<?php
/**
BY COLANDUS @ OTFANS.NET / OTLAND.NET
I r0X!!
*/
include "vars.php";
class Code
{
private $name;
private $tags;
private $attr;
protected $attributes = array("type", "keys", "tag", "color", "read_case", "break_newline");
public function __construct($name)
{
// if is string
$this->name = $name;
}
public static function warning($msg)
{
$dbt = debug_backtrace();
$d = $dbt[count($dbt) - 1];
die("<b>Warning</b>: function $d[class]::$d[function] in file <b>$d[file]</b> on line <b>$d[line]</b></b> $msg!");
}
public function setTags($start, $end, $readcase = false)
{
if (!(is_string($start) && is_string($end) && is_bool($readcase)))
$this->warning("wrong datatype for argument");
$this->tags = array($start, $end, $readcase);
}
public function setAttributes($attr)
{
is_array($this->attr) and $this->warning("attributes already set");
foreach($attr as $name => $words)
if(count($words) == 0)
$this->warning("array with name \"$name\" is empty");
if(is_array($words))
foreach($words as $key => $word)
if(!in_array(strtolower($key), $this->attributes, true))
$this->warning("invalid attribute key \"$key\"");
$this->attr[$name] = $words;
}
public function parse($text)
{
if(!(is_array($this->attr) && is_array($this->tags)))
$this->warning("tags or attributes not set");
foreach($this->attr as $name => $arr)
{
foreach($arr as $k => $v)
switch(strtolower($k))
{
case 'keys':
if(!is_array($v))
$this->warning("expecting array for attribute \"keys\"");
elseif(sizeof($v) == 0)
$this->warning("array of attribute \"keys\" is empty!");
$pattern = '/(';
foreach($v as $str)
{
if(!$prev)
$prev = true;
else
$pattern .= '|';
$pattern .= preg_quote($str);
}
$pattern .= ')/';
break;
case 'color':
$replace = "<font color=\"$v\">\\1</font>";
break;
case 'tag':
if(!is_array($v) || count($v) < 2 || !(is_string($v[0]) && is_string($v[1])))
$this->warning("requiring 2 strings for tags");
if(isset($replace))
$replace = "$v[0]$replace$v[1]";
else
$replace = "$v[0]\\1$v[1]";
break;
case 'read_case':
if(!is_bool($v))
$this->warning("requiring boolean for \"read_case\"");
$read_case = $v;
break;
default:
// echo $k;
break;
}
}
if(!isset($replace))
$this->warning("replace pattern is empty");
if(!isset($read_case))
$pattern .= 'i';
$text = "<pre>" . preg_replace($pattern, $replace, $text) . "</pre>";
echo $text;
}
}
$luaCode = new Code("Lua");
$luaCode->setTags("[code=lua]", "[/code]");
$attr = array(
"Comment" => array(
"KEYS" => array("cid"),
"COLOR" => "green",
"TYPE" => "SINGLE_LINE_COMMENT"
),
"Instruction Word" => array(
"KEYS" => array('and', 'break', 'do', 'true', 'then', 'if', 'elseif', 'else', 'end'),
"COLOR" => 'blue',
"TAG" => array('<b>', '</b>'),
"READ_CASE" => true
)
);
$luaCode->setAttributes($attr);
$codeTest = "
if(isPlayer(cid) == true)then
print \"Hello World!\"
end
";
$luaCode->parse($codeTest);
?>