Completed
Push — master ( 836e6a...8af692 )
by Adam
03:17
created

Phone::addAllowedCountry()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4.5924
Metric Value
dl 0
loc 17
ccs 6
cts 9
cp 0.6667
rs 9.2
cc 4
eloc 9
nc 3
nop 1
crap 4.5924
1
<?php
2
/**
3
 * Phone.php
4
 *
5
 * @copyright      More in license.md
6
 * @license        http://www.ipublikuj.eu
7
 * @author         Adam Kadlec <[email protected]>
8
 * @package        iPublikuj:FormPhone!
9
 * @subpackage     Controls
10
 * @since          1.0.0
11
 *
12
 * @date           15.12.15
13
 */
14
15
namespace IPub\FormPhone\Controls;
16
17
use Nette;
18
use Nette\Forms;
19
use Nette\Localization;
20
use Nette\Utils;
21
22
use IPub;
23
use IPub\FormPhone;
24
use IPub\FormPhone\Exceptions;
25
26
use IPub\Phone\Phone as PhoneUtils;
27 1
28 1
use libphonenumber;
29
use libphonenumber\geocoding;
30
31
/**
32
 * Form phone control element
33
 *
34
 * @package        iPublikuj:FormPhone!
35
 * @subpackage     Controls
36
 *
37
 * @author         Adam Kadlec <[email protected]>
38
 *
39
 * @property-read string $emptyValue
40
 * @property-read Nette\Forms\Rules $rules
41
 */
42
class Phone extends Forms\Controls\TextInput
43
{
44 1
	/**
45
	 * Define filed attributes
46
	 */
47
	const FIELD_COUNTRY = 'country';
48
	const FIELD_NUMBER = 'number';
49
50
	/**
51
	 * @var IPub\Phone\Phone
52
	 */
53
	private $phoneUtils;
54
55
	/**
56
	 * List of allowed countries
57
	 *
58
	 * @var array
59
	 */
60
	private $allowedCountries = [];
61
62 1
	/**
63
	 * List of allowed phone types
64
	 *
65
	 * @var array
66
	 */
67
	private $allowedTypes = [];
68
69
	/**
70
	 * @var string|NULL
71
	 */
72
	private $number = NULL;
73
74
	/**
75
	 * @var string|NULL
76
	 */
77
	private $country = NULL;
78
79
	/**
80
	 * @var string
81
	 */
82
	private $defaultCountry;
83
84
	/**
85
	 * @var bool
86
	 */
87
	private static $registered = FALSE;
88
89 1
	/**
90
	 * @param PhoneUtils $phoneUtils
91
	 * @param string|NULL $label
92
	 * @param int|NULL $maxLength
93
	 */
94
	public function __construct(PhoneUtils $phoneUtils, $label = NULL, $maxLength = NULL)
95
	{
96
		parent::__construct($label, $maxLength);
97 1
98
		$this->phoneUtils = $phoneUtils;
99 1
	}
100 1
101
	/**
102
	 * @param array $countries
103
	 *
104
	 * @return $this
105
	 *
106
	 * @throws Exceptions\NoValidCountryException
107
	 */
108
	public function setAllowedCountries(array $countries = [])
109
	{
110
		$this->allowedCountries = [];
111 1
112
		foreach($countries as $country)
113 1
		{
114
			$country = $this->validateCountry($country);
115 1
			$this->allowedCountries[] = strtoupper($country);
116 1
		}
117 1
118
		// Check for auto country detection
119
		if (in_array('AUTO', $this->allowedCountries)) {
120 1
			$this->allowedCountries = ['AUTO'];
121
		}
122
123
		// Remove duplicities
124
		array_unique($this->allowedCountries);
125 1
126
		return $this;
127 1
	}
128
129
	/**
130
	 * @param string $country
131
	 *
132
	 * @return $this
133 1
	 *
134
	 * @throws Exceptions\NoValidCountryException
135
	 */
136
	public function addAllowedCountry($country)
137
	{
138
		$country = $this->validateCountry($country);
139 1
		$this->allowedCountries[] = strtoupper($country);
140 1
141
		// Remove duplicities
142
		array_unique($this->allowedCountries);
143 1
144
		if (strtoupper($country) === 'AUTO') {
145 1
			$this->allowedCountries = ['AUTO'];
146
147
		} else if (($key = array_search('AUTO', $this->allowedCountries)) && $key !== FALSE) {
148 1
			unset($this->allowedCountries[$key]);
149
		}
150
151
		return $this;
152 1
	}
153
154
	/**
155
	 * @return array
156
	 */
157
	public function getAllowedCountries()
158
	{
159
		if (in_array('AUTO', $this->allowedCountries, TRUE) || $this->allowedCountries === []) {
160 1
			return $this->phoneUtils->getSupportedCountries();
161 1
162
		} else {
163
			return $this->allowedCountries;
164 1
		}
165
	}
166
167
	/**
168
	 * @param string|NULL $country
169
	 *
170
	 * @return $this
171
	 *
172
	 * @throws Exceptions\NoValidCountryException
173
	 */
174
	public function setDefaultCountry($country = NULL)
175
	{
176
		if ($country === NULL) {
177 1
			$this->defaultCountry = NULL;
178 1
179
		} else {
180 1
			$country = $this->validateCountry($country);
181 1
182
			$this->defaultCountry = strtoupper($country);
183 1
		}
184 1
185
		return $this;
186 1
	}
187
188
	/**
189 1
	 * @param array $types
190 1
	 *
191
	 * @return $this
192
	 *
193
	 * @throws Exceptions\NoValidTypeException
194
	 */
195
	public function setAllowedPhoneTypes(array $types = [])
196
	{
197
		$this->allowedTypes = [];
198
199
		foreach($types as $type)
200
		{
201
			$type = $this->validateType($type);
202
			$this->allowedTypes[] = strtoupper($type);
203
		}
204
205
		// Remove duplicities
206
		array_unique($this->allowedTypes);
207
208
		return $this;
209
	}
210
211
	/**
212
	 * @param string $type
213
	 *
214
	 * @return $this
215
	 *
216
	 * @throws Exceptions\NoValidTypeException
217
	 */
218
	public function addAllowedPhoneType($type)
219
	{
220
		$type = $this->validateType($type);
221 1
		$this->allowedTypes[] = strtoupper($type);
222 1
223
		// Remove duplicities
224
		array_unique($this->allowedTypes);
225 1
226
		return $this;
227 1
	}
228
229
	/**
230
	 * @return array
231
	 */
232
	public function getAllowedPhoneTypes()
233
	{
234
		return $this->allowedTypes;
235 1
	}
236
237
	/**
238
	 * @param string
239
	 *
240
	 * @return $this
241
	 *
242
	 * @throws Exceptions\InvalidArgumentException
243
	 */
244
	public function setValue($value)
245
	{
246
		if ($value === NULL) {
247 1
			$this->country = NULL;
248 1
			$this->number = NULL;
249 1
250
			return $this;
251 1
		}
252
253
		foreach($this->getAllowedCountries() as $country) {
254 1
			if ($this->phoneUtils->isValid($value, $country)) {
255 1
				$phone = $this->phoneUtils->parse($value, $country);
256 1
257
				$this->country = $phone->getCountry();
258 1
				$this->number = str_replace(' ', '', $phone->getNationalNumber());
259 1
260
				return $this;
261 1
			}
262
		}
263 1
264
		throw new Exceptions\InvalidArgumentException('Provided value is not valid phone number, or is out of list of allowed countries, "' . $value . '" given.');
265 1
	}
266
267
	/**
268
	 * @return IPub\Phone\Entities\Phone|NULL
269
	 */
270
	public function getValue()
271
	{
272
		if ($this->country === NULL || $this->number === NULL) {
273 1
			return NULL;
274 1
		}
275
276
		try {
277
			// Try to parse number & country
278 1
			$number = $this->phoneUtils->parse($this->number, $this->country);
279 1
280
			return $number === NULL ? NULL : $number;
281
282 1
		} catch (IPub\Phone\Exceptions\NoValidCountryException $ex) {
283 1
			return NULL;
284
285
		} catch (IPub\Phone\Exceptions\NoValidPhoneException $ex) {
286 1
			return NULL;
287
		}
288
	}
289
290
	/**
291
	 * Loads HTTP data
292
	 *
293
	 * @return void
294
	 */
295
	public function loadHttpData()
296 1
	{
297 1
		$country = $this->getHttpData(Forms\Form::DATA_LINE, '[' . static::FIELD_COUNTRY . ']');
298 1
		$this->country = ($country === '' || $country === NULL) ? NULL : (string) $country;
299
300
		$number = $this->getHttpData(Forms\Form::DATA_LINE, '[' . static::FIELD_NUMBER . ']');
301
		$this->number = ($number === '' || $number === NULL) ? NULL : (string) $number;
302
	}
303
304
	/**
305 1
	 * @return Utils\Html
306 1
	 */
307 1
	public function getControl()
308
	{
309 1
		return Utils\Html::el()
310
			->add($this->getControlPart(static::FIELD_COUNTRY) . $this->getControlPart(static::FIELD_NUMBER));
311
	}
312
313
	/**
314
	 * @param string $key
315
	 *
316
	 * @return Utils\Html
317 1
	 *
318
	 * @throws Exceptions\InvalidArgumentException
319 1
	 */
320
	public function getControlPart($key)
321
	{
322 1
		$name = $this->getHtmlName();
323
324
		// Try to get translator
325 1
		$translator = $this->getTranslator();
326 1
327 1
		if ($translator instanceof Localization\ITranslator && method_exists($translator, 'getLocale') === TRUE) {
328 1
			try {
329 1
				$locale = $translator->getLocale();
0 ignored issues
show
Bug introduced by
The method getLocale() does not seem to exist on object<Nette\Localization\ITranslator>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
330
331 1
			} catch (\Exception $ex) {
332
				$locale = 'en_US';
333 1
			}
334 1
335 1
		} else {
336 1
			$locale = 'en_US';
337 1
		}
338 1
339
		if ($key === static::FIELD_COUNTRY) {
340 1
			$control = Forms\Helpers::createSelectBox(
341 1
				array_reduce($this->getAllowedCountries(), function (array $result, $row) use ($locale) {
342
					$countryName = geocoding\Locale::getDisplayRegion(
343 1
						geocoding\Locale::countryCodeToLocale($row),
344
						$locale
345 1
					);
346
347
					$result[$row] = Utils\Html::el('option')
348 1
						->setText('+' . $this->phoneUtils->getCountryCodeForCountry($row) . ' ('. $countryName . ')')
349 1
						->addAttributes([
350 1
							'data-mask' => preg_replace('/[0-9]/', '9', $this->phoneUtils->getExampleNationalNumber($row)),
351 1
						])
352 1
						->value($row);
353 1
354
					return $result;
355 1
				}, []),
356
				[
357
					'selected?' => $this->country === NULL ? $this->defaultCountry : $this->country,
358
				]
359 1
			);
360
361 1
			$control
362 1
				->name($name . '[' . static::FIELD_COUNTRY . ']')
363
				->id($this->getHtmlId() . '-' . static::FIELD_COUNTRY)
364 1
				->{'data-ipub-forms-phone'}('')
365
				->{'data-settings'}(json_encode([
366
					'field' => $name . '[' . static::FIELD_NUMBER . ']'
367 1
				]));
368 1
369 1
			if ($this->isDisabled()) {
370 1
				$control->disabled(TRUE);
371 1
			}
372
373 1
			return $control;
374
375
		} else if ($key === static::FIELD_NUMBER) {
376
			$input = parent::getControl();
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (getControl() instead of getControlPart()). Are you sure this is correct? If so, you might want to change this to $this->getControl().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
377 1
378
			$control = Utils\Html::el('input');
379
380
			$control->addAttributes([
381
				'name'	=> $name . '[' . static::FIELD_NUMBER . ']',
382
				'id'	=> $this->getHtmlId() . '-' . static::FIELD_NUMBER,
383
				'value'	=> $this->number,
384
				'type'	=> 'text',
385
386
				'data-nette-empty-value'	=> Utils\Strings::trim($this->translate($this->emptyValue)),
387
				'data-nette-rules'			=> $input->{'data-nette-rules'},
388
			]);
389
390
			if ($this->isDisabled()) {
391
				$control->disabled(TRUE);
392
			}
393
394
			return $control;
395
		}
396
397
		throw new Exceptions\InvalidArgumentException('Part ' . $key . ' does not exist.');
398
	}
399
400
	/**
401 1
	 * @return NULL
402
	 */
403 1
	public function getLabelPart()
404 1
	{
405
		return NULL;
406
	}
407 1
408
	/**
409
	 * @param string $country
410
	 *
411
	 * @return string
412
	 *
413
	 * @throws Exceptions\NoValidCountryException
414
	 */
415
	protected function validateCountry($country)
416
	{
417
		// Country code have to be upper-cased
418
		$country = strtoupper($country);
419
420
		if ((strlen($country) === 2 && ctype_alpha($country) && ctype_upper($country) && in_array($country, $this->phoneUtils->getSupportedCountries())) || $country === 'AUTO') {
421 1
			return $country;
422
423 1
		} else {
424 1
			throw new Exceptions\NoValidCountryException('Provided country code "' . $country . '" is not valid. Provide valid country code or AUTO for automatic detection.');
425
		}
426
	}
427
428
	/**
429
	 * @param string $type
430
	 *
431
	 * @return string
432
	 *
433
	 * @throws Exceptions\NoValidTypeException
434
	 */
435
	protected function validateType($type)
436
	{
437
		// Phone type have to be upper-cased
438 1
		$type = strtoupper($type);
439 1
440
		if (defined('\IPub\Phone\Phone::TYPE_' . $type)) {
441
			return $type;
442 1
443
		} else {
444 1
			throw new Exceptions\NoValidTypeException('Provided phone type "' . $type . '" is not valid. Provide valid phone type.');
445 1
		}
446 1
	}
447 1
448 1
	/**
449
	 * @param PhoneUtils $phoneUtils
450 1
	 * @param string $method
451
	 */
452 1
	public static function register(PhoneUtils $phoneUtils, $method = 'addPhone')
453 1
	{
454
		// Check for multiple registration
455 1
		if (self::$registered) {
456
			throw new Nette\InvalidStateException('Phone control already registered.');
457
		}
458
459
		self::$registered = TRUE;
460
461
		$class = function_exists('get_called_class') ? get_called_class() : __CLASS__;
462
		Forms\Container::extensionMethod(
463
			$method, function (Forms\Container $form, $name, $label = NULL, $maxLength = NULL) use ($class, $phoneUtils) {
464
			$component = new $class($phoneUtils, $label, $maxLength);
465
			$form->addComponent($component, $name);
466
467
			return $component;
468
		}
469
		);
470
	}
471
}
472