-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExceptionHandler.php
More file actions
105 lines (93 loc) · 2.46 KB
/
ExceptionHandler.php
File metadata and controls
105 lines (93 loc) · 2.46 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
<?php
/**
* A simple exception handler.
*
* @author Fabien Nouaillat
* @version 1.1
*/
class ExceptionHandler
{
protected $file;
protected $line;
protected $message;
protected $template;
protected $type;
/**
* Turns on exception handling.
*
* @param $template The path of the template file
*
* @throws InvalidArgumentException if the file cannot be found
*/
public function start($template)
{
// Checks the file
if (!is_file($template)):
throw new \InvalidArgumentException(sprintf(
'The file %s cannot be found.', $template
));
endif;
// Launches the output buffer
ob_start();
$this->template = $template;
set_exception_handler(array($this, 'register'));
}
/**
* Turns off exception handling and restores the previous configuration.
*
*/
public function stop()
{
// Shuts down the output buffer
ob_end_flush();
restore_exception_handler();
}
/**
* Transforms errors into exceptions
*
* @param mixed $level The degree of error reporting
*/
public function handleErrorsWithLevel($level)
{
error_reporting($level);
set_error_handler(
function($severity, $message, $filename, $lineno) use ($level)
{
throw new \ErrorException(
$message, 0, $severity, $filename, $lineno
);
}
);
}
/**
* Assignes the exception data to the object's properties
*
* @param Object $exception
*/
public function register($exception)
{
$this->file = $exception->getFile();
$this->line = $exception->getLine();
$this->message = $exception->getMessage();
$this->type = get_class($exception);
$this->display();
}
/**
* Calls the template, parse it and display it.
*
*/
protected function display()
{
$stream = file_get_contents($this->template);
$properties = get_object_vars($this);
// Replaces each property by its value
foreach ($properties as $key => $value):
$variable = sprintf('{{ %s }}', $key);
$stream = str_replace($variable, $value, $stream);
endforeach;
// Erases the output buffer
ob_end_clean();
// Displays the template
echo $stream;
}
}