Passed
Push — master ( 1e3687...817005 )
by Sugeng
08:34
created

ToastrFlash::normalizeData()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 10
rs 10
1
<?php
2
3
namespace diecoding\toastr;
4
5
use Yii;
6
use yii\helpers\ArrayHelper;
7
8
/**
9
 * ToastrFlash is a widget integrating the [Toastr](https://codeseven.github.io/toastr/).
10
 * 
11
 * @link [sugeng-sulistiyawan.github.io](sugeng-sulistiyawan.github.io)
12
 * @author Sugeng Sulistiyawan <[email protected]>
13
 * @copyright Copyright (c) 2023
14
 */
15
class ToastrFlash extends ToastrBase
16
{
17
    /**
18
     * @inheritdoc
19
     */
20
    public function run()
21
    {
22
        $allFlashes = Yii::$app->getSession()->getAllFlashes(true);
23
        foreach ($allFlashes as $type => $flash) {
24
            $flashes = (array) $flash;
25
            if (is_array($flashes[0])) {
26
                // Advanced
27
                foreach ($flashes as $data) {
28
                    $normalizedData = $this->normalizeData($data);
29
                    $this->generateToastr($type, $normalizedData['message'], $normalizedData['title'], $normalizedData['options']);
30
                }
31
            } else {
32
                // Simple
33
                foreach ($flashes as $value) {
34
                    $this->generateToastr($type, $value);
35
                }
36
            }
37
        }
38
    }
39
40
    /**
41
     * Generate Single Toastr
42
     * 
43
     * @param string $type
44
     * @param string|null $message
45
     * @param string|null $title
46
     * @param array $options
47
     * @return void
48
     */
49
    private function generateToastr($type, $message = null, $title = null, $options = [])
50
    {
51
        Toastr::widget([
52
            "type" => $type,
53
            "title" => $title,
54
            "message" => $message,
55
            "options" => $options,
56
        ]);
57
    }
58
59
    /**
60
     * Normalize Data Flash Session
61
     * 
62
     * @param array $data
63
     * @return array
64
     */
65
    private function normalizeData($data)
66
    {
67
        $title = $data['title'] ?? (isset($data[1]) ? ($data[0] ?? null) : null);
68
        $message = $data['message'] ?? ($data[1] ?? ($data[0] ?? null));
69
        $options = $data['options'] ?? (isset($data[2]) ? $data[2] : []);
70
71
        return [
72
            'title' => $title,
73
            'message' => $message,
74
            'options' => ArrayHelper::merge($this->options, (array) $options),
75
        ];
76
    }
77
}
78