Completed
Push — master ( b57c0a...d441ef )
by Adam
02:49 queued 14s
created

Confirmer::setTemplateFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 2
1
<?php
2
/**
3
 * Confirmer.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:ConfirmationDialog!
9
 * @subpackage     Components
10
 * @since          1.0.0
11
 *
12
 * @date           31.03.14
13
 */
14
15
declare(strict_types = 1);
16
17
namespace IPub\ConfirmationDialog\Components;
18
19
use Nette;
20
use Nette\Application;
21
use Nette\Forms;
22
use Nette\Localization;
23
24
use IPub;
25
use IPub\ConfirmationDialog;
26
use IPub\ConfirmationDialog\Exceptions;
27
28
/**
29
 * Confirmation dialog confirmer control
30
 *
31
 * @package        iPublikuj:ConfirmationDialog!
32
 * @subpackage     Components
33
 *
34
 * @property-read string $name
35
 * @property-read string $cssClass
36
 * @property-read string $useAjax
37
 */
38 1
final class Confirmer extends ConfirmerAttributes
39
{
40
	/**
41
	 * Define class name
42
	 */
43
	const CLASS_NAME = __CLASS__;
44
45
	/**
46
	 * @var Control|Nette\ComponentModel\IContainer
47
	 */
48
	private $dialog;
49
50
	/**
51
	 * @param NULL|string $templateFile
52
	 */
53
	public function __construct(string $templateFile = NULL)
54
	{
55 1
		list(, $parent, $name) = func_get_args() + [NULL, NULL, NULL];
56
57 1
		parent::__construct($parent, $name);
58
59 1
		if ($templateFile !== NULL) {
60
			$this->setTemplateFile($templateFile);
61
		}
62 1
	}
63
64
	/**
65
	 * Show current confirmer
66
	 *
67
	 * @param array $params
68
	 * 
69
	 * @return void
70
	 */
71
	public function showConfirm(array $params = [])
72
	{
73
		// Generate protection token
74 1
		$token = $this->generateToken();
75
76
		// Set generated token to form
77 1
		$this['form']['secureToken']->value = $token;
78
79
		// Store token to storage
80 1
		$this->storage->set($token, [
81 1
			'confirmer' => $this->getName(),
82 1
			'params'    => $params,
83
		]);
84
85 1
		if ($this->getQuestion() !== FALSE) {
86
			// Invalidate confirmer snippets
87 1
			$this->redrawControl();
88
			// Invalidate dialog snippets
89 1
			$this->getDialog()->redrawControl();
90
		}
91 1
	}
92
93
	/**
94
	 * Confirm YES clicked
95
	 *
96
	 * @param Forms\Controls\SubmitButton $button
97
	 * 
98
	 * @return void
99
	 *
100
	 * @throws Exceptions\HandlerNotCallableException
101
	 */
102
	public function confirmClicked(Forms\Controls\SubmitButton $button)
103
	{
104
		// Get submitted values from form
105 1
		$values = $button->getForm(TRUE)->getValues();
106
107
		// Get token from post
108 1
		$token = $values->secureToken;
109
110
		try {
111
			// Get values stored in confirmer storage
112 1
			$values = $this->getConfirmerValues($token);
113
			// Remove storage data for current confirmer
114 1
			$this->storage->clear($token);
115
116 1
			$this->getDialog()->resetConfirmer();
117
118 1
			$this->callHandler($this->getDialog()->getParent(), $values['params']);
0 ignored issues
show
Bug introduced by
It seems like $this->getDialog()->getParent() can be null; however, callHandler() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
119
120 1
		} catch (Exceptions\InvalidStateException $ex) {
121
			if (self::$strings['expired'] != '' && $this->getPresenter() instanceof Application\UI\Presenter) {
122
				$this->getPresenter()->flashMessage(self::$strings['expired']);
123
			}
124
		}
125
126
		// Check if request is done via ajax...
127
		if ($this->getPresenter() instanceof Application\UI\Presenter && !$this->getPresenter()->isAjax()) {
128
			// ...if not redirect to actual page
129
			$this->getPresenter()->redirect('this');
130
		}
131
	}
132
133
	/**
134
	 * Confirm NO clicked
135
	 * 
136
	 * @return void
137
	 *
138
	 * @param Forms\Controls\SubmitButton $button
139
	 */
140
	public function cancelClicked(Forms\Controls\SubmitButton $button)
141
	{
142
		// Get submitted values from form
143 1
		$values = $button->getForm(TRUE)->getValues();
144
145
		// Get token from post
146 1
		$token = $values->secureToken;
147
148 1
		if ($this->getConfirmerValues($token)) {
149 1
			$this->storage->clear($token);
150
		}
151
152 1
		$this->getDialog()->resetConfirmer();
153
154
		// Check if request is done via ajax...
155 1
		if ($this->getPresenter() instanceof Application\UI\Presenter && !$this->getPresenter()->isAjax()) {
156
			// ...if not redirect to actual page
157 1
			$this->getPresenter()->redirect('this');
158
		}
159
	}
160
161
	/**
162
	 * Check if confirmer is fully configured
163
	 *
164
	 * @return bool
165
	 */
166
	public function isConfigured() : bool
167
	{
168 1
		if ((is_string($this->heading) || is_callable($this->heading)) &&
169 1
			(is_string($this->question) || is_callable($this->question)) &&
170 1
			is_callable($this->handler)
171
		) {
172 1
			return TRUE;
173
		}
174
175 1
		return FALSE;
176
	}
177
178
	/**
179
	 * Render confirmer
180
	 * 
181
	 * @return void
182
	 *
183
	 * @throws Exceptions\InvalidStateException
184
	 */
185
	public function render()
186
	{
187
		// Create template
188 1
		$template = parent::render();
189
190
		// Check if control has template
191 1
		if ($template instanceof Nette\Bridges\ApplicationLatte\Template) {
192
			// Assign vars to template
193 1
			$template->add('name', $this->name);
194 1
			$template->add('class', $this->cssClass);
195 1
			$template->add('icon', $this->getIcon());
196 1
			$template->add('question', $this->getQuestion());
197 1
			$template->add('heading', $this->getHeading());
198 1
			$template->add('useAjax', $this->useAjax);
199
200
			// If template was not defined before...
201 1
			if ($template->getFile() === NULL) {
202
				// ...try to get base component template file
203 1
				$templateFile = !empty($this->templateFile) ? $this->templateFile : $this->getDialog()->getTemplateFile();
204 1
				$template->setFile($templateFile);
205
			}
206
207
			// Render component template
208 1
			$template->render();
209
210
		} else {
211
			throw new Exceptions\InvalidStateException('Confirmer control is without template.');
212
		}
213 1
	}
214
215
	/**
216
	 * Change default confirmer template path
217
	 *
218
	 * @param string $layoutFile
219
	 * 
220
	 * @return void
221
	 */
222
	public function setTemplateFile(string $layoutFile)
223
	{
224
		$this->setTemplateFilePath($layoutFile, self::TEMPLATE_CONFIRMER);
225
	}
226
227
	/**
228
	 * Generate unique token key
229
	 *
230
	 * @return string
231
	 */
232
	protected function generateToken() : string
233
	{
234 1
		return base_convert(md5(uniqid('confirm' . $this->getName(), TRUE)), 16, 36);
235
	}
236
237
	/**
238
	 * Get parent dialog control
239
	 *
240
	 * @return Control
241
	 *
242
	 * @throws Exceptions\InvalidStateException
243
	 */
244
	protected function getDialog() : Control
245
	{
246
		// Check if confirm dialog was loaded before...
247 1
		if (!$this->dialog) {
248
			// ...if not try to lookup for it
249 1
			$multiplier = $this->getParent();
250
251
			// Check if confirmer is in multiplier
252 1
			if ($multiplier instanceof Application\UI\Multiplier) {
253 1
				$this->dialog = $multiplier->getParent();
254
255
				// Check if parent is right
256 1
				if (!$this->dialog instanceof Control) {
257 1
					throw new Exceptions\InvalidStateException('Confirmer is not attached to parent control!');
258
				}
259
260
			} else {
261
				throw new Exceptions\InvalidStateException('Confirmer is not attached to multiplier!');
262
			}
263
		}
264
265 1
		return $this->dialog;
266
	}
267
}
268