summaryrefslogtreecommitdiffstats
path: root/lib/FileHandler.php
blob: 9b6266a15b32868bfaf9a1202d104487c797f4ba (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
<?php
require 'Reader.php';
require 'CallgrindPreprocessor.php';
class FileHandler{
	private static $singleton = null;
	
	public static function getInstance(){
		if(self::$singleton==null)
			self::$singleton = new FileHandler();
		return self::$singleton;
	}
		
	private function __construct(){
		
		$files = $this->getFiles(Config::$xdebugOutputFormat, Config::$xdebugOutputDir);
		
		$prepFiles = $this->getFiles('/\\'.Config::$preprocessedSuffix.'$/', Config::$storageDir);
		foreach($prepFiles as $fileName=>$prepFile){
			$fileName = str_replace(Config::$preprocessedSuffix,'',$fileName);
			
			if(!isset($files[$fileName]) || $files[$fileName]['mtime']>$prepFile['mtime'] )
				unlink($prepFile['absoluteFilename']);
			else
				$files[$fileName]['preprocessed'] = true;
		}
		uasort($files,array($this,'mtimeCmp'));
		$this->files = $files;
	}
	
	
	public function getInvokeUrl($file){
		# Grab name of invoked file
	    $fp = fopen($file, 'r');
	    fgets($fp);
	    $invokeUrl = trim(substr(fgets($fp), 5));
	    fclose($fp);
		return $invokeUrl;
	}
	
	
	private function getFiles($format, $dir){
		$list = preg_grep($format,scandir($dir));
		$files = array();
		
		$scriptFilename = $_SERVER['SCRIPT_FILENAME'];
		
		foreach($list as $file){
			$absoluteFilename = $dir.$file;
			$invokeUrl = $this->getInvokeUrl($absoluteFilename);

			$files[$file] = array('absoluteFilename'=>$absoluteFilename, 'mtime'=>filemtime($absoluteFilename), 'preprocessed'=>false, 'invokeUrl'=>$invokeUrl, 'selftrace'=>false);
			if($invokeUrl == $scriptFilename)
				$files[$file]['selftrace'] = true;
			
		}		
		return $files;
	}
	
	public function getTraceList($selftraces=false){
		$result = array();
		foreach($this->files as $fileName=>$file){
			if(!$file['selftrace'] || $selftraces)
				$result[] = array('filename' => $fileName, 'invokeUrl' => str_replace($_SERVER['DOCUMENT_ROOT'].'/', '', $file['invokeUrl']));
		}
		return $result;
	}
	
	public function getTraceReader($file){
		$prepFile = Config::$storageDir.$file.Config::$preprocessedSuffix;
		try{
			$r = new Reader($prepFile);
		} catch (Exception $e){
			// Preprocessed file does not exist or other error
			$cg = new CallgrindPreprocessor(Config::$xdebugOutputDir.$file, $prepFile);
			$cg->parse();
			$r = new Reader($prepFile);
		}
		return $r;
	}
	
	private function mtimeCmp($a, $b){
		if ($a['mtime'] == $b['mtime'])
		    return 0;

		return ($a['mtime'] > $b['mtime']) ? -1 : 1;
	}
	
}