1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Core\Modules; |
4
|
|
|
/** |
5
|
|
|
* Gets and sets the alert box message to be sent to the front |
6
|
|
|
* Class AlertBox |
7
|
|
|
* @package Core\Modules |
8
|
|
|
*/ |
9
|
|
|
class AlertBox extends Module |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @var array the diffrent allowed alert types |
13
|
|
|
*/ |
14
|
|
|
private $allowedTypes = [ |
15
|
|
|
'success', |
16
|
|
|
'info', |
17
|
|
|
'warning', |
18
|
|
|
'error' |
19
|
|
|
]; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* sets our alert message |
23
|
|
|
* @param string $message the alert message |
24
|
|
|
* @param string $type the type of alert |
25
|
|
|
* @throws \Exception |
26
|
|
|
*/ |
27
|
|
|
public function setAlert(string $message, $type = 'success'):void |
28
|
|
|
{ |
29
|
|
|
//make sure we have the right type or throw an error |
30
|
|
|
|
31
|
|
|
if (!in_array($type, $this->allowedTypes)) { |
32
|
|
|
throw new \Exception("Invalid toastr alert type " . $type); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
$message = htmlspecialchars($message); //avoid any injection |
36
|
|
|
|
37
|
|
|
$message = [ |
38
|
|
|
'type' => $type, |
39
|
|
|
'message' => $message |
40
|
|
|
]; |
41
|
|
|
$session = $this->container->getSession(); |
42
|
|
|
|
43
|
|
|
|
44
|
|
|
$alert = $session->get('alert_messages'); |
45
|
|
|
|
46
|
|
|
|
47
|
|
|
$alert[] = $message; |
48
|
|
|
|
49
|
|
|
$session->set('alert_messages', $alert); |
50
|
|
|
|
51
|
|
|
|
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Checks if we have any unsent alerts |
56
|
|
|
* @return bool |
57
|
|
|
*/ |
58
|
|
|
public function alertsPending():bool |
59
|
|
|
{ |
60
|
|
|
$session = $this->container->getSession(); |
61
|
|
|
|
62
|
|
|
return $session->isParamSet('alert_messages'); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* grabs the pending alerts from teh session and returns the array |
67
|
|
|
* It then empties the alerts to avoid showing the same alert twice |
68
|
|
|
* @return array |
69
|
|
|
*/ |
70
|
|
|
public function getAlerts(): array |
71
|
|
|
{ |
72
|
|
|
if (!$this->alertsPending()) { |
73
|
|
|
return []; |
74
|
|
|
} |
75
|
|
|
$session = $this->container->getSession(); |
76
|
|
|
$alerts = $session->get('alert_messages'); |
77
|
|
|
//could return null and need to send back an array. this should never happen since we checked the alerts pending but scrutinizer complains ! |
78
|
|
|
if (is_null($alerts)) { |
79
|
|
|
$alerts = []; |
80
|
|
|
} |
81
|
|
|
$session->remove('alert_messages'); |
82
|
|
|
return $alerts; |
83
|
|
|
|
84
|
|
|
|
85
|
|
|
} |
86
|
|
|
} |