Completed
Push — master ( fbee6d...8a36ee )
by Adam
02:56
created

FlashNotifier::important()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 6
rs 9.4286
cc 1
eloc 3
nc 1
nop 0
1
<?php
2
/**
3
 * TFlashMessages.php
4
 *
5
 * @copyright      More in license.md
6
 * @license        http://www.ipublikuj.eu
7
 * @author         Adam Kadlec http://www.ipublikuj.eu
8
 * @package        iPublikuj:FlashMessages!
9
 * @subpackage     common
10
 * @since          1.0.0
11
 *
12
 * @date           01.02.15
13
 */
14
15
namespace IPub\FlashMessages;
16
17
use Nette;
18
use Nette\Localization;
19
20
use Kdyby;
21
use Kdyby\Translation;
22
23
use IPub;
24
use IPub\FlashMessages\Adapters;
25
use IPub\FlashMessages\Entities;
26
27
/**
28
 * Flash message notifier
29
 *
30
 * @package        iPublikuj:FlashMessages!
31
 * @subpackage     common
32
 *
33
 * @author         Adam Kadlec <[email protected]>
34
 */
35
class FlashNotifier extends Nette\Object
36
{
37
	/**
38
	 * @var SessionStorage
39
	 */
40
	protected $sessionStorage;
41
42
	/**
43
	 * @var Localization\ITranslator
44
	 */
45
	protected $translator;
46
47
	/**
48
	 * @param SessionStorage $sessionStorage
49
	 * @param Localization\ITranslator $translator
50
	 */
51
	public function __construct(SessionStorage $sessionStorage, Localization\ITranslator $translator = NULL)
52
	{
53
		$this->sessionStorage = $sessionStorage;
54
		$this->translator = $translator;
55
	}
56
57
	/**
58
	 * Flash a success message
59
	 *
60
	 * @param string $message
61
	 * @param string|null $title
62
	 *
63
	 * @return $this
64
	 */
65
	public function success($message, $title = NULL)
66
	{
67
		$this->message($message, 'success', $title);
68
69
		return $this;
70
	}
71
72
	/**
73
	 * Flash an information message
74
	 *
75
	 * @param string $message
76
	 * @param string|null $title
77
	 *
78
	 * @return $this
79
	 */
80
	public function info($message, $title = NULL)
81
	{
82
		$this->message($message, 'info', $title);
83
84
		return $this;
85
	}
86
87
	/**
88
	 * Flash a warning message
89
	 *
90
	 * @param string $message
91
	 * @param string|null $title
92
	 *
93
	 * @return $this
94
	 */
95
	public function warning($message, $title = NULL)
96
	{
97
		$this->message($message, 'warning', $title);
98
99
		return $this;
100
	}
101
102
	/**
103
	 * Flash an error message
104
	 *
105
	 * @param string $message
106
	 * @param string|null $title
107
	 *
108
	 * @return $this
109
	 */
110
	public function error($message, $title = NULL)
111
	{
112
		$this->message($message, 'danger', $title);
113
114
		return $this;
115
	}
116
117
	/**
118
	 * Add an "important" flash to the session
119
	 *
120
	 * @return $this
121
	 */
122
	public function important()
123
	{
124
		$this->sessionStorage->set(SessionStorage::KEY_IMPORTANT, TRUE);
125
126
		return $this;
127
	}
128
129
	/**
130
	 * Flash an overlay modal
131
	 *
132
	 * @param string $message
133
	 * @param string $title
134
	 *
135
	 * @return $this
136
	 */
137
	public function overlay($message, $title = 'Notice')
138
	{
139
		$this->message($message, 'info', $title, TRUE);
140
141
		return $this;
142
	}
143
144
	/**
145
	 * Flash a general message
146
	 *
147
	 * @param string $message
148
	 * @param string $level
149
	 * @param string $title
150
	 * @param boolean $overlay
151
	 * @param int|null $count
152
	 * @param array $parameters
153
	 *
154
	 * @return Entities\IMessage
155
	 */
156
	public function message($message, $level = 'info', $title = 'Notice', $overlay = FALSE, $count = NULL, array $parameters = [])
157
	{
158
		$title = $this->checkForAttribute([$title, $overlay, $count, $parameters], 'title');
159
		$overlay = $this->checkForAttribute([$title, $overlay, $count, $parameters], 'overlay');
160
		$count = $this->checkForAttribute([$title, $overlay, $count, $parameters], 'count');
161
		$parameters = $this->checkForAttribute([$title, $overlay, $count, $parameters], 'parameters');
162
163
		// Support for Kdyby/Translation
164
		if ($message instanceof Translation\Phrase) {
0 ignored issues
show
Bug introduced by
The class Kdyby\Translation\Phrase does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
165
			$phrase = new Adapters\KdybyPhraseAdapter($message);
166
167
			// Default phrase adapter
168
		} else if (!$message instanceof Adapters\IPhraseAdapter) {
169
			$phrase = new Adapters\DefaultPhraseAdapter($message, $count, $parameters);
170
		}
171
172
		// Support for Kdyby/Translation
173
		if ($title instanceof Translation\Phrase) {
0 ignored issues
show
Bug introduced by
The class Kdyby\Translation\Phrase does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
174
			$titlePhrase = new Adapters\KdybyPhraseAdapter($title);
175
176
		// Default phrase adapter
177
		} else if (!$title instanceof Adapters\IPhraseAdapter && $title !== NULL) {
178
			$titlePhrase = new Adapters\DefaultPhraseAdapter($title, $count, $parameters);
179
180
		} else {
181
			$titlePhrase = NULL;
182
		}
183
184
		// Get all stored messages
185
		$messages = $this->sessionStorage->get(SessionStorage::KEY_MESSAGES, []);
186
187
		// Create flash message
188
		$flash = (new Entities\Message($this->translator, $phrase, $titlePhrase))
0 ignored issues
show
Bug introduced by
The variable $phrase does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
189
			->setLevel($level)
190
			->setOverlay($overlay);
191
192
		if (!$this->translator instanceof Localization\ITranslator) {
193
			$flash->setMessage($message);
194
			$flash->setTitle($title);
195
		}
196
197
		if ($this->checkUnique($flash, $messages) === FALSE) {
198
			$messages[] = $flash;
199
		}
200
201
		// Store messages in session
202
		$this->sessionStorage->set(SessionStorage::KEY_MESSAGES, $messages);
203
204
		return $flash;
205
	}
206
207
	/**
208
	 * @param Entities\IMessage $flash
209
	 * @param Entities\IMessage[] $messages
210
	 *
211
	 * @return bool
212
	 */
213
	private function checkUnique(Entities\IMessage $flash, array $messages)
214
	{
215
		foreach ($messages as $member) {
216
			if ((string) $member === (string) $flash) {
217
				return TRUE;
218
			}
219
		}
220
221
		return FALSE;
222
	}
223
224
	/**
225
	 * @param array $attributes
226
	 * @param string $type
227
	 *
228
	 * @return mixed
229
	 */
230
	private function checkForAttribute(array $attributes, $type)
231
	{
232
		foreach($attributes as $attribute) {
233
			switch($type)
234
			{
235
				case 'title':
236
					if (is_string($attribute) === TRUE || $attribute instanceof Translation\Phrase || $attribute instanceof Adapters\IPhraseAdapter) {
0 ignored issues
show
Bug introduced by
The class Kdyby\Translation\Phrase does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
237
						return $attribute;
238
					}
239
					break;
240
241
				case 'overlay':
242
					if (is_bool($attribute) === TRUE) {
243
						return $attribute;
244
					}
245
					break;
246
247
				case 'count':
248
					if (is_numeric($attribute) === TRUE) {
249
						return $attribute;
250
					}
251
					break;
252
253
				case 'parameters':
254
					if (is_array($attribute) === TRUE) {
255
						return $attribute;
256
					}
257
					break;
258
			}
259
		}
260
261
		return NULL;
262
	}
263
}
264