1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace M6Web\Bundle\ApiExceptionBundle\Exception; |
4
|
|
|
|
5
|
|
|
use M6Web\Bundle\ApiExceptionBundle\Exception\Interfaces\ExceptionInterface; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* class Exception |
9
|
|
|
*/ |
10
|
|
|
class Exception extends \Exception implements ExceptionInterface |
11
|
|
|
{ |
12
|
|
|
const VARIABLE_REGEX = "/(\{[a-zA-Z0-9\_]+\})/"; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Constructor |
16
|
|
|
* |
17
|
|
|
* @param integer $code |
18
|
|
|
* @param string $message |
19
|
|
|
*/ |
20
|
|
|
public function __construct( |
21
|
|
|
$code = 0, |
22
|
|
|
$message = '' |
23
|
|
|
) { |
24
|
1 |
|
parent::__construct($message, $code); |
25
|
1 |
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Set code |
29
|
|
|
* |
30
|
|
|
* @param integer $code |
31
|
|
|
* |
32
|
|
|
* @return self |
33
|
|
|
*/ |
34
|
|
|
public function setCode($code) |
35
|
|
|
{ |
36
|
|
|
$this->code = $code; |
37
|
|
|
|
38
|
|
|
return $this; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Set message |
43
|
|
|
* |
44
|
|
|
* @param string $message |
45
|
|
|
* |
46
|
|
|
* @return self |
47
|
|
|
*/ |
48
|
|
|
public function setMessage($message) |
49
|
|
|
{ |
50
|
|
|
$this->message = $message; |
51
|
|
|
|
52
|
|
|
return $this; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* Get message with variables |
57
|
|
|
* |
58
|
|
|
* @throws \Exception |
59
|
|
|
* |
60
|
|
|
* @return string |
61
|
|
|
*/ |
62
|
|
|
public function getMessageWithVariables() |
63
|
|
|
{ |
64
|
1 |
|
$message = $this->message; |
65
|
|
|
|
66
|
1 |
|
preg_match(self::VARIABLE_REGEX, $message, $variables); |
67
|
|
|
|
68
|
1 |
|
foreach ($variables as $variable) { |
69
|
1 |
|
$variableName = substr($variable, 1, -1); |
70
|
|
|
|
71
|
1 |
|
if (!isset($this->$variableName)) { |
72
|
1 |
|
throw new \Exception(sprintf( |
73
|
1 |
|
'Variable "%s" for exception "%s" not found', |
74
|
1 |
|
$variableName, |
75
|
1 |
|
get_class($this) |
76
|
1 |
|
), 500); |
77
|
|
|
} |
78
|
|
|
|
79
|
1 |
|
if (!is_string($this->$variableName)) { |
80
|
1 |
|
throw new \Exception(sprintf( |
81
|
1 |
|
'Variable "%s" for exception "%s" must be a string, %s found', |
82
|
1 |
|
$variableName, |
83
|
1 |
|
get_class($this), |
84
|
1 |
|
gettype($this->$variableName) |
85
|
1 |
|
), 500); |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
$message = str_replace($variable, $this->$variableName, $message); |
89
|
|
|
} |
90
|
|
|
|
91
|
|
|
return $message; |
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
|