<?php
 namespace Engine\Logger; class Xml extends GeneralAbstract { private $directory = null; private $fullFilePath = null; private $rootTag = "errorLog"; public function __construct() { parent::__construct(); global $CFG; $this->directory = realpath($CFG['logger']['pathToRoot'])."/"; } public function setFullFilePath($fullFilePath) { $this->fullFilePath = $fullFilePath; } public function getFullFilePath() { return $this->fullFilePath; } public function writeRawMessage($fields) { $fullFilePath = $this->fullFilePath; if ($fullFilePath===null) { $monthDir = date("Ym").'/'; $filename = sprintf("%s.xml", date("Y-m-d")); if (!\Engine\Dir::check($this->directory.$monthDir)) { \Engine\Dir::create($this->directory.$monthDir); } $fullFilePath = $this->directory.$monthDir.$filename; } if (!\Engine\File::check($fullFilePath)) { $xml = simplexml_load_string("<?xml version=\"1.0\" encoding=\"UTF-8\"?><".$this->rootTag."></".$this->rootTag.">"); $errXml = $xml->addChild('error'); $errXml = $this->composeXmlError($errXml, $fields['level'], $fields['message'], $fields['context'], $fields['stacktrace'], $fields['idUser'], $fields['addTime'], $fields['logSession']); $xml->asXML($fullFilePath); } else { $tempTag = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; $errXml = simplexml_load_string("{$tempTag}<error></error>"); $errXml = $this->composeXmlError($errXml, $fields['level'], $fields['message'], $fields['context'], $fields['stacktrace'], $fields['idUser'], $fields['addTime'], $fields['logSession']); $xmlStr = str_replace($tempTag, '', $errXml->asXML()); $fh = fopen($fullFilePath, 'a+'); $stat = fstat($fh); ftruncate($fh, $stat['size']-(strlen($this->rootTag)+4)); fwrite($fh, $xmlStr."</".$this->rootTag.">"); fclose($fh); } return true; } private function composeXmlError($errXml, $level, $message, $context, $stacktrace, $idUser, $addTime, $logSession) { $errXml->addTime = $addTime; $errXml->level = $level; $errXml->logSession = $logSession; $errXml->message = $message; $errXml->context = ''; $this->composeContext($errXml->context, $context); $errXml->stacktrace = ''; $this->composeStacktrace($errXml->stacktrace, $stacktrace); $errXml->idUser = $idUser; return $errXml; } private function composeStacktrace($xmlStack, Array $stacktrace) { $prefixIgnore = realpath(MODULE_REL_PATH).'/'; foreach ($stacktrace as $step) { $xmlStack->addChild("trace", sprintf("%s:%s, %s->%s()\n", str_replace($prefixIgnore, "", $step['file']), $step['line'], $step['class'], $step['function'])); } return $xmlStack; } private function composeContext($xmlCtx, Array $context) { foreach ($context as $key=>$value) { if (is_object($value) || is_array($value) || is_resource($value)) { $xmlValue = serialize($value); } else { $xmlValue = (string)$value; } $xmlParam = $xmlCtx->addChild("param", $xmlValue); $xmlParam['name'] = $key; $xmlParam['type'] = gettype($value); } return $xmlCtx; } } 