1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace PerfectApp\Flash; |
6
|
|
|
|
7
|
|
|
class FlashMessage |
8
|
|
|
{ |
9
|
|
|
private mixed $messages; |
10
|
|
|
|
11
|
|
|
private array $config; |
12
|
|
|
|
13
|
5 |
|
public function __construct($config) |
14
|
|
|
{ |
15
|
5 |
|
$this->config = $config; |
16
|
5 |
|
$_SESSION['flash'] = []; |
17
|
5 |
|
$this->messages = $_SESSION['flash']; |
18
|
5 |
|
$_SESSION['flash'] = []; |
19
|
|
|
} |
20
|
|
|
|
21
|
4 |
|
public function set($type, $action, $icon = ''): array |
22
|
|
|
{ |
23
|
4 |
|
$allowedTypes = ['primary', 'secondary', 'light', 'dark', 'success', 'info', 'warning', 'danger']; |
24
|
|
|
|
25
|
4 |
|
if (!in_array($type, $allowedTypes)) { |
26
|
2 |
|
$message = sprintf('ERROR: Invalid type "%s" provided', $type); |
27
|
2 |
|
$this->messages[] = ['type' => 'danger', 'message' => $message, 'icon' => '']; |
28
|
2 |
|
return $_SESSION['flash'] = $this->messages; |
29
|
|
|
} |
30
|
|
|
|
31
|
2 |
|
if (!isset($this->config[$type][$action])) { |
32
|
1 |
|
$message = sprintf('ERROR: Invalid action "%s" provided', $action); |
33
|
1 |
|
$this->messages[] = ['type' => 'danger', 'message' => $message, 'icon' => '']; |
34
|
1 |
|
return $_SESSION['flash'] = $this->messages; |
35
|
|
|
} |
36
|
|
|
|
37
|
1 |
|
$message = $this->config[$type][$action]; |
38
|
1 |
|
$this->messages[] = ['type' => $type, 'message' => $message, 'icon' => $icon]; |
39
|
1 |
|
return $_SESSION['flash'] = $this->messages; |
40
|
|
|
} |
41
|
|
|
|
42
|
4 |
|
public function display(): void |
43
|
|
|
{ |
44
|
4 |
|
foreach ($this->messages as $message) { |
45
|
4 |
|
printf( |
46
|
4 |
|
'<div class="alert alert-%s alert-dismissible fade show" role="alert">%s <strong>%s</strong> |
47
|
4 |
|
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>', |
48
|
|
|
|
49
|
4 |
|
$message['type'], |
50
|
4 |
|
$message['icon'], |
51
|
4 |
|
$message['message'] |
52
|
4 |
|
); |
53
|
|
|
} |
54
|
4 |
|
$_SESSION['flash'] = []; |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|