Completed
Push — master ( d81690...79b790 )
by Propa
02:58
created
src/Validation/Phone.php 1 patch
Indentation   +131 added lines, -131 removed lines patch added patch discarded remove patch
@@ -11,135 +11,135 @@
 block discarded – undo
11 11
 
12 12
 class Phone
13 13
 {
14
-    use ParsesCountries,
15
-        ParsesTypes;
16
-
17
-    /**
18
-     * @var \libphonenumber\PhoneNumberUtil
19
-     */
20
-    protected $lib;
21
-
22
-    /**
23
-     * Phone constructor.
24
-     */
25
-    public function __construct()
26
-    {
27
-        $this->lib = PhoneNumberUtil::getInstance();
28
-    }
29
-
30
-    /**
31
-     * Validates a phone number.
32
-     *
33
-     * @param  string $attribute
34
-     * @param  mixed  $value
35
-     * @param  array  $parameters
36
-     * @param  object $validator
37
-     * @return bool
38
-     */
39
-    public function validate($attribute, $value, array $parameters, $validator)
40
-    {
41
-        $data = $validator->getData();
42
-
43
-        list(
44
-            $countries,
45
-            $types,
46
-            $detect,
47
-            $lenient) = $this->extractParameters($attribute, $parameters, $data);
48
-
49
-        // A "null" country is prepended:
50
-        // 1. In case of auto-detection to have the validation run first without supplying a country.
51
-        // 2. In case of lenient validation without provided countries; we still might have some luck...
52
-        if ($detect || ($lenient && empty($countries))) {
53
-            array_unshift($countries, null);
54
-        }
55
-
56
-        foreach ($countries as $country) {
57
-            try {
58
-                // Parsing the phone number also validates the country, so no need to do this explicitly.
59
-                // It'll throw a PhoneCountryException upon failure.
60
-                $phoneNumber = PhoneNumber::make($value, $country);
61
-
62
-                // Type validation.
63
-                if (! empty($types) && ! $phoneNumber->isOfType($types)) {
64
-                    continue;
65
-                }
66
-
67
-                $lenientPhoneNumber = $phoneNumber->lenient()->getPhoneNumberInstance();
68
-
69
-                // Lenient validation.
70
-                if ($lenient && $this->lib->isPossibleNumber($lenientPhoneNumber, $country)) {
71
-                    return true;
72
-                }
73
-
74
-                $phoneNumberInstance = $phoneNumber->getPhoneNumberInstance();
75
-
76
-                // Country detection.
77
-                if ($detect && $this->lib->isValidNumber($phoneNumberInstance)) {
78
-                    return true;
79
-                }
80
-
81
-                // Default number+country validation.
82
-                if ($this->lib->isValidNumberForRegion($phoneNumberInstance, $country)) {
83
-                    return true;
84
-                }
85
-            } catch (NumberParseException $e) {
86
-                continue;
87
-            }
88
-        }
89
-
90
-        return false;
91
-    }
92
-
93
-    /**
94
-     * Parse and extract parameters in the appropriate validation arguments.
95
-     *
96
-     * @param string $attribute
97
-     * @param array  $parameters
98
-     * @param array  $data
99
-     * @return array
100
-     * @throws \Propaganistas\LaravelPhone\Exceptions\InvalidParameterException
101
-     */
102
-    protected function extractParameters($attribute, array $parameters, array $data)
103
-    {
104
-        // Discover if an input field was provided. If not, guess the field's name.
105
-        $inputField = Collection::make($parameters)
106
-                                ->intersect(array_keys(Arr::dot($data)))
107
-                                ->first() ?: "${attribute}_country";
108
-
109
-        // Attempt to retrieve the field's value.
110
-        if ($inputCountry = Arr::get($data, $inputField)) {
111
-
112
-            if (static::isValidType($inputField)) {
113
-                throw InvalidParameterException::ambiguous($inputField);
114
-            }
115
-
116
-            // Invalid country field values should just validate to false, and this is exactly what
117
-            // we're getting when simply excluding invalid values.
118
-            // This will also prevent parameter hijacking through the country field.
119
-            if (static::isValidCountryCode($inputCountry)) {
120
-                $parameters[] = $inputCountry;
121
-            }
122
-        }
123
-
124
-        $countries = static::parseCountries($parameters);
125
-        $types = static::parseTypes($parameters);
126
-
127
-        // Force developers to write proper code.
128
-        // Since the static parsers return a validated array with preserved keys, we can safely diff against the keys.
129
-        // Unfortunately we can't use $collection->diffKeys() as it's not available yet in earlier 5.* versions.
130
-        $leftovers = array_diff_key($parameters, $types, $countries);
131
-        $leftovers = array_diff($leftovers, ['AUTO', 'LENIENT', $inputField]);
132
-
133
-        if (! empty($leftovers)) {
134
-            throw InvalidParameterException::parameters($leftovers);
135
-        }
136
-
137
-        return [
138
-            $countries,
139
-            $types,
140
-            in_array('AUTO', $parameters),
141
-            in_array('LENIENT', $parameters),
142
-            $inputField,
143
-        ];
144
-    }
14
+	use ParsesCountries,
15
+		ParsesTypes;
16
+
17
+	/**
18
+	 * @var \libphonenumber\PhoneNumberUtil
19
+	 */
20
+	protected $lib;
21
+
22
+	/**
23
+	 * Phone constructor.
24
+	 */
25
+	public function __construct()
26
+	{
27
+		$this->lib = PhoneNumberUtil::getInstance();
28
+	}
29
+
30
+	/**
31
+	 * Validates a phone number.
32
+	 *
33
+	 * @param  string $attribute
34
+	 * @param  mixed  $value
35
+	 * @param  array  $parameters
36
+	 * @param  object $validator
37
+	 * @return bool
38
+	 */
39
+	public function validate($attribute, $value, array $parameters, $validator)
40
+	{
41
+		$data = $validator->getData();
42
+
43
+		list(
44
+			$countries,
45
+			$types,
46
+			$detect,
47
+			$lenient) = $this->extractParameters($attribute, $parameters, $data);
48
+
49
+		// A "null" country is prepended:
50
+		// 1. In case of auto-detection to have the validation run first without supplying a country.
51
+		// 2. In case of lenient validation without provided countries; we still might have some luck...
52
+		if ($detect || ($lenient && empty($countries))) {
53
+			array_unshift($countries, null);
54
+		}
55
+
56
+		foreach ($countries as $country) {
57
+			try {
58
+				// Parsing the phone number also validates the country, so no need to do this explicitly.
59
+				// It'll throw a PhoneCountryException upon failure.
60
+				$phoneNumber = PhoneNumber::make($value, $country);
61
+
62
+				// Type validation.
63
+				if (! empty($types) && ! $phoneNumber->isOfType($types)) {
64
+					continue;
65
+				}
66
+
67
+				$lenientPhoneNumber = $phoneNumber->lenient()->getPhoneNumberInstance();
68
+
69
+				// Lenient validation.
70
+				if ($lenient && $this->lib->isPossibleNumber($lenientPhoneNumber, $country)) {
71
+					return true;
72
+				}
73
+
74
+				$phoneNumberInstance = $phoneNumber->getPhoneNumberInstance();
75
+
76
+				// Country detection.
77
+				if ($detect && $this->lib->isValidNumber($phoneNumberInstance)) {
78
+					return true;
79
+				}
80
+
81
+				// Default number+country validation.
82
+				if ($this->lib->isValidNumberForRegion($phoneNumberInstance, $country)) {
83
+					return true;
84
+				}
85
+			} catch (NumberParseException $e) {
86
+				continue;
87
+			}
88
+		}
89
+
90
+		return false;
91
+	}
92
+
93
+	/**
94
+	 * Parse and extract parameters in the appropriate validation arguments.
95
+	 *
96
+	 * @param string $attribute
97
+	 * @param array  $parameters
98
+	 * @param array  $data
99
+	 * @return array
100
+	 * @throws \Propaganistas\LaravelPhone\Exceptions\InvalidParameterException
101
+	 */
102
+	protected function extractParameters($attribute, array $parameters, array $data)
103
+	{
104
+		// Discover if an input field was provided. If not, guess the field's name.
105
+		$inputField = Collection::make($parameters)
106
+								->intersect(array_keys(Arr::dot($data)))
107
+								->first() ?: "${attribute}_country";
108
+
109
+		// Attempt to retrieve the field's value.
110
+		if ($inputCountry = Arr::get($data, $inputField)) {
111
+
112
+			if (static::isValidType($inputField)) {
113
+				throw InvalidParameterException::ambiguous($inputField);
114
+			}
115
+
116
+			// Invalid country field values should just validate to false, and this is exactly what
117
+			// we're getting when simply excluding invalid values.
118
+			// This will also prevent parameter hijacking through the country field.
119
+			if (static::isValidCountryCode($inputCountry)) {
120
+				$parameters[] = $inputCountry;
121
+			}
122
+		}
123
+
124
+		$countries = static::parseCountries($parameters);
125
+		$types = static::parseTypes($parameters);
126
+
127
+		// Force developers to write proper code.
128
+		// Since the static parsers return a validated array with preserved keys, we can safely diff against the keys.
129
+		// Unfortunately we can't use $collection->diffKeys() as it's not available yet in earlier 5.* versions.
130
+		$leftovers = array_diff_key($parameters, $types, $countries);
131
+		$leftovers = array_diff($leftovers, ['AUTO', 'LENIENT', $inputField]);
132
+
133
+		if (! empty($leftovers)) {
134
+			throw InvalidParameterException::parameters($leftovers);
135
+		}
136
+
137
+		return [
138
+			$countries,
139
+			$types,
140
+			in_array('AUTO', $parameters),
141
+			in_array('LENIENT', $parameters),
142
+			$inputField,
143
+		];
144
+	}
145 145
 }
Please login to merge, or discard this patch.
src/PhoneNumber.php 1 patch
Indentation   +374 added lines, -374 removed lines patch added patch discarded remove patch
@@ -19,378 +19,378 @@
 block discarded – undo
19 19
 
20 20
 class PhoneNumber implements Jsonable, JsonSerializable, Serializable
21 21
 {
22
-    use ParsesCountries,
23
-        ParsesFormats,
24
-        ParsesTypes;
25
-
26
-    /**
27
-     * The provided phone number.
28
-     *
29
-     * @var string
30
-     */
31
-    protected $number;
32
-
33
-    /**
34
-     * The provided phone country.
35
-     *
36
-     * @var array
37
-     */
38
-    protected $countries = [];
39
-
40
-    /**
41
-     * The detected phone country.
42
-     *
43
-     * @var string
44
-     */
45
-    protected $country;
46
-
47
-    /**
48
-     * Whether to allow lenient checks (i.e. landline numbers without area codes).
49
-     *
50
-     * @var bool
51
-     */
52
-    protected $lenient = false;
53
-
54
-    /**
55
-     * @var \libphonenumber\PhoneNumberUtil
56
-     */
57
-    protected $lib;
58
-
59
-    /**
60
-     * Phone constructor.
61
-     *
62
-     * @param string $number
63
-     */
64
-    public function __construct($number)
65
-    {
66
-        $this->number = $number;
67
-        $this->lib = PhoneNumberUtil::getInstance();
68
-    }
69
-
70
-    /**
71
-     * Create a phone instance.
72
-     *
73
-     * @param string       $number
74
-     * @param string|array $country
75
-     * @return static
76
-     */
77
-    public static function make($number, $country = [])
78
-    {
79
-        $instance = new static($number);
80
-
81
-        return $instance->ofCountry($country);
82
-    }
83
-
84
-    /**
85
-     * Set the country to which the phone number belongs to.
86
-     *
87
-     * @param string|array $country
88
-     * @return static
89
-     */
90
-    public function ofCountry($country)
91
-    {
92
-        $countries = is_array($country) ? $country : func_get_args();
93
-
94
-        $instance = clone $this;
95
-        $instance->countries = array_unique(
96
-            array_merge($instance->countries, static::parseCountries($countries))
97
-        );
98
-
99
-        return $instance;
100
-    }
101
-
102
-    /**
103
-     * Format the phone number in international format.
104
-     *
105
-     * @return string
106
-     */
107
-    public function formatInternational()
108
-    {
109
-        return $this->format(PhoneNumberFormat::INTERNATIONAL);
110
-    }
111
-
112
-    /**
113
-     * Format the phone number in national format.
114
-     *
115
-     * @return string
116
-     */
117
-    public function formatNational()
118
-    {
119
-        return $this->format(PhoneNumberFormat::NATIONAL);
120
-    }
121
-
122
-    /**
123
-     * Format the phone number in E164 format.
124
-     *
125
-     * @return string
126
-     */
127
-    public function formatE164()
128
-    {
129
-        return $this->format(PhoneNumberFormat::E164);
130
-    }
131
-
132
-    /**
133
-     * Format the phone number in RFC3966 format.
134
-     *
135
-     * @return string
136
-     */
137
-    public function formatRFC3966()
138
-    {
139
-        return $this->format(PhoneNumberFormat::RFC3966);
140
-    }
141
-
142
-    /**
143
-     * Format the phone number in a given format.
144
-     *
145
-     * @param string $format
146
-     * @return string
147
-     * @throws \Propaganistas\LaravelPhone\Exceptions\NumberFormatException
148
-     */
149
-    public function format($format)
150
-    {
151
-        $parsedFormat = static::parseFormat($format);
152
-
153
-        if (is_null($parsedFormat)) {
154
-            throw NumberFormatException::invalid($format);
155
-        }
156
-
157
-        return $this->lib->format(
158
-            $this->getPhoneNumberInstance(),
159
-            $parsedFormat
160
-        );
161
-    }
162
-
163
-    /**
164
-     * Format the phone number in a way that it can be dialled from the provided country.
165
-     *
166
-     * @param string $country
167
-     * @return string
168
-     * @throws \Propaganistas\LaravelPhone\Exceptions\CountryCodeException
169
-     */
170
-    public function formatForCountry($country)
171
-    {
172
-        if (! static::isValidCountryCode($country)) {
173
-            throw CountryCodeException::invalid($country);
174
-        }
175
-
176
-        return $this->lib->formatOutOfCountryCallingNumber(
177
-            $this->getPhoneNumberInstance(),
178
-            $country
179
-        );
180
-    }
181
-
182
-    /**
183
-     * Format the phone number in a way that it can be dialled from the provided country using a cellphone.
184
-     *
185
-     * @param string $country
186
-     * @param bool   $removeFormatting
187
-     * @return string
188
-     * @throws \Propaganistas\LaravelPhone\Exceptions\CountryCodeException
189
-     */
190
-    public function formatForMobileDialingInCountry($country, $removeFormatting = false)
191
-    {
192
-        if (! static::isValidCountryCode($country)) {
193
-            throw CountryCodeException::invalid($country);
194
-        }
195
-
196
-        return $this->lib->formatNumberForMobileDialing(
197
-            $this->getPhoneNumberInstance(),
198
-            $country,
199
-            $removeFormatting
200
-        );
201
-    }
202
-
203
-    /**
204
-     * Get the phone number's country.
205
-     *
206
-     * @return string
207
-     */
208
-    public function getCountry()
209
-    {
210
-        if (! $this->country) {
211
-            $this->country = $this->filterValidCountry($this->countries);
212
-        }
213
-
214
-        return $this->country;
215
-    }
216
-
217
-    /**
218
-     * Check if the phone number is of (a) given country(ies).
219
-     *
220
-     * @param string|array $country
221
-     * @return bool
222
-     */
223
-    public function isOfCountry($country)
224
-    {
225
-        $countries = static::parseCountries($country);
226
-
227
-        return in_array($this->getCountry(), $countries);
228
-    }
229
-
230
-    /**
231
-     * Filter the provided countries to the one that is valid for the number.
232
-     *
233
-     * @param string|array $countries
234
-     * @return string
235
-     * @throws \Propaganistas\LaravelPhone\Exceptions\NumberParseException
236
-     */
237
-    protected function filterValidCountry($countries)
238
-    {
239
-        $result = Collection::make($countries)
240
-                            ->filter(function ($country) {
241
-                                $instance = $this->lib->parse($this->number, $country);
242
-
243
-                                return $this->lenient
244
-                                    ? $this->lib->isPossibleNumber($instance, $country)
245
-                                    : $this->lib->isValidNumberForRegion($instance, $country);
246
-                            })->first();
247
-
248
-        // If we got a new result, return it.
249
-        if ($result) {
250
-            return $result;
251
-        }
252
-
253
-        // Last resort: try to detect it from an international number.
254
-        if ($this->numberLooksInternational()) {
255
-            $countries[] = null;
256
-        }
257
-
258
-        foreach ($countries as $country) {
259
-            $instance = $this->lib->parse($this->number, $country);
260
-
261
-            if ($this->lib->isValidNumber($instance)) {
262
-                return $this->lib->getRegionCodeForNumber($instance);
263
-            }
264
-        }
265
-
266
-        throw NumberParseException::countryRequired($this->number);
267
-    }
268
-
269
-    /**
270
-     * Get the phone number's type.
271
-     *
272
-     * @param bool $asConstant
273
-     * @return string|int|null
274
-     */
275
-    public function getType($asConstant = false)
276
-    {
277
-        $type = $this->lib->getNumberType($this->getPhoneNumberInstance());
278
-
279
-        if ($asConstant) {
280
-            return $type;
281
-        }
282
-
283
-        $stringType = Arr::get(static::parseTypesAsStrings($type), 0);
284
-
285
-        return $stringType ? strtolower($stringType) : null;
286
-    }
287
-
288
-    /**
289
-     * Check if the phone number is of (a) given type(s).
290
-     *
291
-     * @param string $type
292
-     * @return bool
293
-     */
294
-    public function isOfType($type)
295
-    {
296
-        $types = static::parseTypes($type);
297
-
298
-        // Add the unsure type when applicable.
299
-        if (array_intersect([PhoneNumberType::FIXED_LINE, PhoneNumberType::MOBILE], $types)) {
300
-            $types[] = PhoneNumberType::FIXED_LINE_OR_MOBILE;
301
-        }
302
-
303
-        return in_array($this->getType(true), $types, true);
304
-    }
305
-
306
-    /**
307
-     * Get the PhoneNumber instance of the current number.
308
-     *
309
-     * @return \libphonenumber\PhoneNumber
310
-     */
311
-    public function getPhoneNumberInstance()
312
-    {
313
-        return $this->lib->parse($this->number, $this->getCountry());
314
-    }
315
-
316
-    /**
317
-     * Determine whether the phone number seems to be in international format.
318
-     *
319
-     * @return bool
320
-     */
321
-    protected function numberLooksInternational()
322
-    {
323
-        return Str::startsWith($this->number, '+');
324
-    }
325
-
326
-    /**
327
-     * Enable lenient number parsing.
328
-     *
329
-     * @return $this
330
-     */
331
-    public function lenient()
332
-    {
333
-        $this->lenient = true;
334
-
335
-        return $this;
336
-    }
337
-
338
-    /**
339
-     * Convert the phone instance to JSON.
340
-     *
341
-     * @param  int $options
342
-     * @return string
343
-     */
344
-    public function toJson($options = 0)
345
-    {
346
-        return json_encode($this->jsonSerialize(), $options);
347
-    }
348
-
349
-    /**
350
-     * Convert the phone instance into something JSON serializable.
351
-     *
352
-     * @return string
353
-     */
354
-    public function jsonSerialize()
355
-    {
356
-        return $this->formatE164();
357
-    }
358
-
359
-    /**
360
-     * Convert the phone instance into a string representation.
361
-     *
362
-     * @return string
363
-     */
364
-    public function serialize()
365
-    {
366
-        return $this->formatE164();
367
-    }
368
-
369
-    /**
370
-     * Reconstructs the phone instance from a string representation.
371
-     *
372
-     * @param string $serialized
373
-     */
374
-    public function unserialize($serialized)
375
-    {
376
-        $this->lib = PhoneNumberUtil::getInstance();
377
-        $this->number = $serialized;
378
-        $this->country = $this->lib->getRegionCodeForNumber($this->getPhoneNumberInstance());
379
-    }
380
-
381
-    /**
382
-     * Convert the phone instance to a formatted number.
383
-     *
384
-     * @return string
385
-     */
386
-    public function __toString()
387
-    {
388
-        // Formatting the phone number could throw an exception, but __toString() doesn't cope well with that.
389
-        // Let's just return the original number in that case.
390
-        try {
391
-            return $this->formatE164();
392
-        } catch (Exception $exception) {
393
-            return $this->number;
394
-        }
395
-    }
22
+	use ParsesCountries,
23
+		ParsesFormats,
24
+		ParsesTypes;
25
+
26
+	/**
27
+	 * The provided phone number.
28
+	 *
29
+	 * @var string
30
+	 */
31
+	protected $number;
32
+
33
+	/**
34
+	 * The provided phone country.
35
+	 *
36
+	 * @var array
37
+	 */
38
+	protected $countries = [];
39
+
40
+	/**
41
+	 * The detected phone country.
42
+	 *
43
+	 * @var string
44
+	 */
45
+	protected $country;
46
+
47
+	/**
48
+	 * Whether to allow lenient checks (i.e. landline numbers without area codes).
49
+	 *
50
+	 * @var bool
51
+	 */
52
+	protected $lenient = false;
53
+
54
+	/**
55
+	 * @var \libphonenumber\PhoneNumberUtil
56
+	 */
57
+	protected $lib;
58
+
59
+	/**
60
+	 * Phone constructor.
61
+	 *
62
+	 * @param string $number
63
+	 */
64
+	public function __construct($number)
65
+	{
66
+		$this->number = $number;
67
+		$this->lib = PhoneNumberUtil::getInstance();
68
+	}
69
+
70
+	/**
71
+	 * Create a phone instance.
72
+	 *
73
+	 * @param string       $number
74
+	 * @param string|array $country
75
+	 * @return static
76
+	 */
77
+	public static function make($number, $country = [])
78
+	{
79
+		$instance = new static($number);
80
+
81
+		return $instance->ofCountry($country);
82
+	}
83
+
84
+	/**
85
+	 * Set the country to which the phone number belongs to.
86
+	 *
87
+	 * @param string|array $country
88
+	 * @return static
89
+	 */
90
+	public function ofCountry($country)
91
+	{
92
+		$countries = is_array($country) ? $country : func_get_args();
93
+
94
+		$instance = clone $this;
95
+		$instance->countries = array_unique(
96
+			array_merge($instance->countries, static::parseCountries($countries))
97
+		);
98
+
99
+		return $instance;
100
+	}
101
+
102
+	/**
103
+	 * Format the phone number in international format.
104
+	 *
105
+	 * @return string
106
+	 */
107
+	public function formatInternational()
108
+	{
109
+		return $this->format(PhoneNumberFormat::INTERNATIONAL);
110
+	}
111
+
112
+	/**
113
+	 * Format the phone number in national format.
114
+	 *
115
+	 * @return string
116
+	 */
117
+	public function formatNational()
118
+	{
119
+		return $this->format(PhoneNumberFormat::NATIONAL);
120
+	}
121
+
122
+	/**
123
+	 * Format the phone number in E164 format.
124
+	 *
125
+	 * @return string
126
+	 */
127
+	public function formatE164()
128
+	{
129
+		return $this->format(PhoneNumberFormat::E164);
130
+	}
131
+
132
+	/**
133
+	 * Format the phone number in RFC3966 format.
134
+	 *
135
+	 * @return string
136
+	 */
137
+	public function formatRFC3966()
138
+	{
139
+		return $this->format(PhoneNumberFormat::RFC3966);
140
+	}
141
+
142
+	/**
143
+	 * Format the phone number in a given format.
144
+	 *
145
+	 * @param string $format
146
+	 * @return string
147
+	 * @throws \Propaganistas\LaravelPhone\Exceptions\NumberFormatException
148
+	 */
149
+	public function format($format)
150
+	{
151
+		$parsedFormat = static::parseFormat($format);
152
+
153
+		if (is_null($parsedFormat)) {
154
+			throw NumberFormatException::invalid($format);
155
+		}
156
+
157
+		return $this->lib->format(
158
+			$this->getPhoneNumberInstance(),
159
+			$parsedFormat
160
+		);
161
+	}
162
+
163
+	/**
164
+	 * Format the phone number in a way that it can be dialled from the provided country.
165
+	 *
166
+	 * @param string $country
167
+	 * @return string
168
+	 * @throws \Propaganistas\LaravelPhone\Exceptions\CountryCodeException
169
+	 */
170
+	public function formatForCountry($country)
171
+	{
172
+		if (! static::isValidCountryCode($country)) {
173
+			throw CountryCodeException::invalid($country);
174
+		}
175
+
176
+		return $this->lib->formatOutOfCountryCallingNumber(
177
+			$this->getPhoneNumberInstance(),
178
+			$country
179
+		);
180
+	}
181
+
182
+	/**
183
+	 * Format the phone number in a way that it can be dialled from the provided country using a cellphone.
184
+	 *
185
+	 * @param string $country
186
+	 * @param bool   $removeFormatting
187
+	 * @return string
188
+	 * @throws \Propaganistas\LaravelPhone\Exceptions\CountryCodeException
189
+	 */
190
+	public function formatForMobileDialingInCountry($country, $removeFormatting = false)
191
+	{
192
+		if (! static::isValidCountryCode($country)) {
193
+			throw CountryCodeException::invalid($country);
194
+		}
195
+
196
+		return $this->lib->formatNumberForMobileDialing(
197
+			$this->getPhoneNumberInstance(),
198
+			$country,
199
+			$removeFormatting
200
+		);
201
+	}
202
+
203
+	/**
204
+	 * Get the phone number's country.
205
+	 *
206
+	 * @return string
207
+	 */
208
+	public function getCountry()
209
+	{
210
+		if (! $this->country) {
211
+			$this->country = $this->filterValidCountry($this->countries);
212
+		}
213
+
214
+		return $this->country;
215
+	}
216
+
217
+	/**
218
+	 * Check if the phone number is of (a) given country(ies).
219
+	 *
220
+	 * @param string|array $country
221
+	 * @return bool
222
+	 */
223
+	public function isOfCountry($country)
224
+	{
225
+		$countries = static::parseCountries($country);
226
+
227
+		return in_array($this->getCountry(), $countries);
228
+	}
229
+
230
+	/**
231
+	 * Filter the provided countries to the one that is valid for the number.
232
+	 *
233
+	 * @param string|array $countries
234
+	 * @return string
235
+	 * @throws \Propaganistas\LaravelPhone\Exceptions\NumberParseException
236
+	 */
237
+	protected function filterValidCountry($countries)
238
+	{
239
+		$result = Collection::make($countries)
240
+							->filter(function ($country) {
241
+								$instance = $this->lib->parse($this->number, $country);
242
+
243
+								return $this->lenient
244
+									? $this->lib->isPossibleNumber($instance, $country)
245
+									: $this->lib->isValidNumberForRegion($instance, $country);
246
+							})->first();
247
+
248
+		// If we got a new result, return it.
249
+		if ($result) {
250
+			return $result;
251
+		}
252
+
253
+		// Last resort: try to detect it from an international number.
254
+		if ($this->numberLooksInternational()) {
255
+			$countries[] = null;
256
+		}
257
+
258
+		foreach ($countries as $country) {
259
+			$instance = $this->lib->parse($this->number, $country);
260
+
261
+			if ($this->lib->isValidNumber($instance)) {
262
+				return $this->lib->getRegionCodeForNumber($instance);
263
+			}
264
+		}
265
+
266
+		throw NumberParseException::countryRequired($this->number);
267
+	}
268
+
269
+	/**
270
+	 * Get the phone number's type.
271
+	 *
272
+	 * @param bool $asConstant
273
+	 * @return string|int|null
274
+	 */
275
+	public function getType($asConstant = false)
276
+	{
277
+		$type = $this->lib->getNumberType($this->getPhoneNumberInstance());
278
+
279
+		if ($asConstant) {
280
+			return $type;
281
+		}
282
+
283
+		$stringType = Arr::get(static::parseTypesAsStrings($type), 0);
284
+
285
+		return $stringType ? strtolower($stringType) : null;
286
+	}
287
+
288
+	/**
289
+	 * Check if the phone number is of (a) given type(s).
290
+	 *
291
+	 * @param string $type
292
+	 * @return bool
293
+	 */
294
+	public function isOfType($type)
295
+	{
296
+		$types = static::parseTypes($type);
297
+
298
+		// Add the unsure type when applicable.
299
+		if (array_intersect([PhoneNumberType::FIXED_LINE, PhoneNumberType::MOBILE], $types)) {
300
+			$types[] = PhoneNumberType::FIXED_LINE_OR_MOBILE;
301
+		}
302
+
303
+		return in_array($this->getType(true), $types, true);
304
+	}
305
+
306
+	/**
307
+	 * Get the PhoneNumber instance of the current number.
308
+	 *
309
+	 * @return \libphonenumber\PhoneNumber
310
+	 */
311
+	public function getPhoneNumberInstance()
312
+	{
313
+		return $this->lib->parse($this->number, $this->getCountry());
314
+	}
315
+
316
+	/**
317
+	 * Determine whether the phone number seems to be in international format.
318
+	 *
319
+	 * @return bool
320
+	 */
321
+	protected function numberLooksInternational()
322
+	{
323
+		return Str::startsWith($this->number, '+');
324
+	}
325
+
326
+	/**
327
+	 * Enable lenient number parsing.
328
+	 *
329
+	 * @return $this
330
+	 */
331
+	public function lenient()
332
+	{
333
+		$this->lenient = true;
334
+
335
+		return $this;
336
+	}
337
+
338
+	/**
339
+	 * Convert the phone instance to JSON.
340
+	 *
341
+	 * @param  int $options
342
+	 * @return string
343
+	 */
344
+	public function toJson($options = 0)
345
+	{
346
+		return json_encode($this->jsonSerialize(), $options);
347
+	}
348
+
349
+	/**
350
+	 * Convert the phone instance into something JSON serializable.
351
+	 *
352
+	 * @return string
353
+	 */
354
+	public function jsonSerialize()
355
+	{
356
+		return $this->formatE164();
357
+	}
358
+
359
+	/**
360
+	 * Convert the phone instance into a string representation.
361
+	 *
362
+	 * @return string
363
+	 */
364
+	public function serialize()
365
+	{
366
+		return $this->formatE164();
367
+	}
368
+
369
+	/**
370
+	 * Reconstructs the phone instance from a string representation.
371
+	 *
372
+	 * @param string $serialized
373
+	 */
374
+	public function unserialize($serialized)
375
+	{
376
+		$this->lib = PhoneNumberUtil::getInstance();
377
+		$this->number = $serialized;
378
+		$this->country = $this->lib->getRegionCodeForNumber($this->getPhoneNumberInstance());
379
+	}
380
+
381
+	/**
382
+	 * Convert the phone instance to a formatted number.
383
+	 *
384
+	 * @return string
385
+	 */
386
+	public function __toString()
387
+	{
388
+		// Formatting the phone number could throw an exception, but __toString() doesn't cope well with that.
389
+		// Let's just return the original number in that case.
390
+		try {
391
+			return $this->formatE164();
392
+		} catch (Exception $exception) {
393
+			return $this->number;
394
+		}
395
+	}
396 396
 }
397 397
\ No newline at end of file
Please login to merge, or discard this patch.