Completed
Push — master ( a5cb0c...3d23f6 )
by Propa
02:35
created
src/PhoneValidator.php 1 patch
Indentation   +201 added lines, -201 removed lines patch added patch discarded remove patch
@@ -10,206 +10,206 @@
 block discarded – undo
10 10
 class PhoneValidator
11 11
 {
12 12
 
13
-    /**
14
-     * The phone number attribute.
15
-     *
16
-     * @var string
17
-     */
18
-    protected $attribute;
19
-
20
-    /**
21
-     * Data from the validator instance.
22
-     *
23
-     * @var array
24
-     */
25
-    protected $data;
26
-
27
-    /**
28
-     * Countries to validate against.
29
-     *
30
-     * @var array
31
-     */
32
-    protected $allowedCountries = [];
33
-
34
-    /**
35
-     * Untransformed phone number types to validate against.
36
-     *
37
-     * @var array
38
-     */
39
-    protected $untransformedTypes = [];
40
-
41
-    /**
42
-     * Transformed phone number types to validate against.
43
-     *
44
-     * @var array
45
-     */
46
-    protected $allowedTypes = [];
47
-
48
-    /**
49
-     * Supplied validator parameters.
50
-     *
51
-     * @var array
52
-     */
53
-    protected $parameters;
54
-
55
-    /**
56
-     * Validates a phone number.
57
-     *
58
-     * @param  string                                     $attribute
59
-     * @param  mixed                                      $value
60
-     * @param  array                                      $parameters
61
-     * @param  \Illuminate\Contracts\Validation\Validator $validator
62
-     * @return bool
63
-     * @throws \Propaganistas\LaravelPhone\Exceptions\InvalidParameterException
64
-     * @throws \Propaganistas\LaravelPhone\Exceptions\NoValidCountryFoundException
65
-     */
66
-    public function validatePhone($attribute, $value, array $parameters, Validator $validator)
67
-    {
68
-        $this->attribute = $attribute;
69
-        $this->data = $validator->getData();
70
-        $this->parameters = array_map('strtoupper', $parameters);
71
-
72
-        $this->determineCountries();
73
-        $this->determineTypes();
74
-        $this->checkLeftoverParameters();
75
-
76
-        $phoneUtil = PhoneNumberUtil::getInstance();
77
-
78
-        // Perform validation.
79
-        foreach ($this->allowedCountries as $country) {
80
-            try {
81
-                // For default countries or country field, the following throws NumberParseException if
82
-                // not parsed correctly against the supplied country.
83
-                // For automatic detection: tries to discover the country code using from the number itself.
84
-                $phoneProto = $phoneUtil->parse($value, $country);
85
-
86
-                // For automatic detection, the number should have a country code.
87
-                // Check if type is allowed.
88
-                if ($phoneProto->hasCountryCode() && empty($this->allowedTypes) || in_array($phoneUtil->getNumberType($phoneProto),
89
-                        $this->allowedTypes)
90
-                ) {
91
-
92
-                    // Automatic detection:
93
-                    if ($country == 'ZZ') {
94
-                        // Validate if the international phone number is valid for its contained country.
95
-                        return $phoneUtil->isValidNumber($phoneProto);
96
-                    }
97
-
98
-                    // Validate number against the specified country.  Return only if success.
99
-                    // If failure, continue loop to next specfied country
100
-                    $success = $phoneUtil->isValidNumberForRegion($phoneProto, $country);
101
-
102
-                    if ($success) {
103
-                        return true;
104
-                    }
105
-                }
106
-
107
-            } catch (NumberParseException $e) {
108
-                // Proceed to default validation error.
109
-            }
110
-        }
111
-
112
-        // All specified country validations have failed.
113
-        return false;
114
-    }
115
-
116
-    /**
117
-     * Checks if the supplied string is a valid country code using some arbitrary country validation.
118
-     * If using a package based on umpirsky/country-list, invalidate the option 'ZZ => Unknown or invalid region'.
119
-     *
120
-     * @param  string $country
121
-     * @return bool
122
-     */
123
-    public function isPhoneCountry($country)
124
-    {
125
-        return (strlen($country) === 2 && ctype_alpha($country) && ctype_upper($country) && $country != 'ZZ');
126
-    }
127
-
128
-    /**
129
-     * Checks if the supplied string is a valid phone number type.
130
-     *
131
-     * @param  string $type
132
-     * @return bool
133
-     */
134
-    public function isPhoneType($type)
135
-    {
136
-        // Legacy support.
137
-        $type = ($type == 'LANDLINE' ? 'FIXED_LINE' : $type);
138
-
139
-        return defined($this->constructPhoneTypeConstant($type));
140
-    }
141
-
142
-    /**
143
-     * Constructs the corresponding namespaced class constant for a phone number type.
144
-     *
145
-     * @param  string $type
146
-     * @return string
147
-     */
148
-    protected function constructPhoneTypeConstant($type)
149
-    {
150
-        return '\libphonenumber\PhoneNumberType::' . $type;
151
-    }
152
-
153
-    /**
154
-     * Sets the countries to validate against.
155
-     *
156
-     * @throws \Propaganistas\LaravelPhone\Exceptions\NoValidCountryFoundException
157
-     */
158
-    protected function determineCountries()
159
-    {
160
-        // Check for the existence of a country field.
161
-        $field = $this->attribute . '_country';
162
-        if (isset($this->data[$field])) {
163
-            $this->allowedCountries = ($this->isPhoneCountry($this->data[$field])) ? [$this->data[$field]] : [];
164
-            // No exception should be thrown since empty country fields should validate to false.
165
-        } // Or if we need to parse for automatic detection.
166
-        elseif (in_array('AUTO', $this->parameters)) {
167
-            $this->allowedCountries = ['ZZ'];
168
-        } // Else use the supplied parameters.
169
-        else {
170
-            $this->allowedCountries = array_filter($this->parameters, function ($item) {
171
-                return $this->isPhoneCountry($item);
172
-            });
173
-
174
-            if (empty($this->allowedCountries)) {
175
-                throw new NoValidCountryFoundException;
176
-            }
177
-        }
178
-    }
179
-
180
-    /**
181
-     * Sets the phone number types to validate against.
182
-     */
183
-    protected function determineTypes()
184
-    {
185
-        // Get phone types.
186
-        $this->untransformedTypes = array_filter($this->parameters, function ($item) {
187
-            return $this->isPhoneType($item);
188
-        });
189
-
190
-        // Transform valid types to their namespaced class constant.
191
-        $this->allowedTypes = array_map(function ($item) {
192
-            return constant($this->constructPhoneTypeConstant($item));
193
-        }, $this->untransformedTypes);
194
-
195
-        // Add in the unsure number type if applicable.
196
-        if (array_intersect(['FIXED_LINE', 'MOBILE'], $this->parameters)) {
197
-            $this->allowedTypes[] = PhoneNumberType::FIXED_LINE_OR_MOBILE;
198
-        }
199
-    }
200
-
201
-    /**
202
-     * Checks for parameter leftovers to force developers to write proper code.
203
-     *
204
-     * @throws \Propaganistas\LaravelPhone\Exceptions\InvalidParameterException
205
-     */
206
-    protected function checkLeftoverParameters()
207
-    {
208
-        // Remove the automatic detection option if applicable.
209
-        $leftovers = array_diff($this->parameters, $this->allowedCountries, $this->untransformedTypes, array('AUTO'));
210
-        if (!empty($leftovers)) {
211
-            throw new InvalidParameterException(implode(', ', $leftovers));
212
-        }
213
-    }
13
+	/**
14
+	 * The phone number attribute.
15
+	 *
16
+	 * @var string
17
+	 */
18
+	protected $attribute;
19
+
20
+	/**
21
+	 * Data from the validator instance.
22
+	 *
23
+	 * @var array
24
+	 */
25
+	protected $data;
26
+
27
+	/**
28
+	 * Countries to validate against.
29
+	 *
30
+	 * @var array
31
+	 */
32
+	protected $allowedCountries = [];
33
+
34
+	/**
35
+	 * Untransformed phone number types to validate against.
36
+	 *
37
+	 * @var array
38
+	 */
39
+	protected $untransformedTypes = [];
40
+
41
+	/**
42
+	 * Transformed phone number types to validate against.
43
+	 *
44
+	 * @var array
45
+	 */
46
+	protected $allowedTypes = [];
47
+
48
+	/**
49
+	 * Supplied validator parameters.
50
+	 *
51
+	 * @var array
52
+	 */
53
+	protected $parameters;
54
+
55
+	/**
56
+	 * Validates a phone number.
57
+	 *
58
+	 * @param  string                                     $attribute
59
+	 * @param  mixed                                      $value
60
+	 * @param  array                                      $parameters
61
+	 * @param  \Illuminate\Contracts\Validation\Validator $validator
62
+	 * @return bool
63
+	 * @throws \Propaganistas\LaravelPhone\Exceptions\InvalidParameterException
64
+	 * @throws \Propaganistas\LaravelPhone\Exceptions\NoValidCountryFoundException
65
+	 */
66
+	public function validatePhone($attribute, $value, array $parameters, Validator $validator)
67
+	{
68
+		$this->attribute = $attribute;
69
+		$this->data = $validator->getData();
70
+		$this->parameters = array_map('strtoupper', $parameters);
71
+
72
+		$this->determineCountries();
73
+		$this->determineTypes();
74
+		$this->checkLeftoverParameters();
75
+
76
+		$phoneUtil = PhoneNumberUtil::getInstance();
77
+
78
+		// Perform validation.
79
+		foreach ($this->allowedCountries as $country) {
80
+			try {
81
+				// For default countries or country field, the following throws NumberParseException if
82
+				// not parsed correctly against the supplied country.
83
+				// For automatic detection: tries to discover the country code using from the number itself.
84
+				$phoneProto = $phoneUtil->parse($value, $country);
85
+
86
+				// For automatic detection, the number should have a country code.
87
+				// Check if type is allowed.
88
+				if ($phoneProto->hasCountryCode() && empty($this->allowedTypes) || in_array($phoneUtil->getNumberType($phoneProto),
89
+						$this->allowedTypes)
90
+				) {
91
+
92
+					// Automatic detection:
93
+					if ($country == 'ZZ') {
94
+						// Validate if the international phone number is valid for its contained country.
95
+						return $phoneUtil->isValidNumber($phoneProto);
96
+					}
97
+
98
+					// Validate number against the specified country.  Return only if success.
99
+					// If failure, continue loop to next specfied country
100
+					$success = $phoneUtil->isValidNumberForRegion($phoneProto, $country);
101
+
102
+					if ($success) {
103
+						return true;
104
+					}
105
+				}
106
+
107
+			} catch (NumberParseException $e) {
108
+				// Proceed to default validation error.
109
+			}
110
+		}
111
+
112
+		// All specified country validations have failed.
113
+		return false;
114
+	}
115
+
116
+	/**
117
+	 * Checks if the supplied string is a valid country code using some arbitrary country validation.
118
+	 * If using a package based on umpirsky/country-list, invalidate the option 'ZZ => Unknown or invalid region'.
119
+	 *
120
+	 * @param  string $country
121
+	 * @return bool
122
+	 */
123
+	public function isPhoneCountry($country)
124
+	{
125
+		return (strlen($country) === 2 && ctype_alpha($country) && ctype_upper($country) && $country != 'ZZ');
126
+	}
127
+
128
+	/**
129
+	 * Checks if the supplied string is a valid phone number type.
130
+	 *
131
+	 * @param  string $type
132
+	 * @return bool
133
+	 */
134
+	public function isPhoneType($type)
135
+	{
136
+		// Legacy support.
137
+		$type = ($type == 'LANDLINE' ? 'FIXED_LINE' : $type);
138
+
139
+		return defined($this->constructPhoneTypeConstant($type));
140
+	}
141
+
142
+	/**
143
+	 * Constructs the corresponding namespaced class constant for a phone number type.
144
+	 *
145
+	 * @param  string $type
146
+	 * @return string
147
+	 */
148
+	protected function constructPhoneTypeConstant($type)
149
+	{
150
+		return '\libphonenumber\PhoneNumberType::' . $type;
151
+	}
152
+
153
+	/**
154
+	 * Sets the countries to validate against.
155
+	 *
156
+	 * @throws \Propaganistas\LaravelPhone\Exceptions\NoValidCountryFoundException
157
+	 */
158
+	protected function determineCountries()
159
+	{
160
+		// Check for the existence of a country field.
161
+		$field = $this->attribute . '_country';
162
+		if (isset($this->data[$field])) {
163
+			$this->allowedCountries = ($this->isPhoneCountry($this->data[$field])) ? [$this->data[$field]] : [];
164
+			// No exception should be thrown since empty country fields should validate to false.
165
+		} // Or if we need to parse for automatic detection.
166
+		elseif (in_array('AUTO', $this->parameters)) {
167
+			$this->allowedCountries = ['ZZ'];
168
+		} // Else use the supplied parameters.
169
+		else {
170
+			$this->allowedCountries = array_filter($this->parameters, function ($item) {
171
+				return $this->isPhoneCountry($item);
172
+			});
173
+
174
+			if (empty($this->allowedCountries)) {
175
+				throw new NoValidCountryFoundException;
176
+			}
177
+		}
178
+	}
179
+
180
+	/**
181
+	 * Sets the phone number types to validate against.
182
+	 */
183
+	protected function determineTypes()
184
+	{
185
+		// Get phone types.
186
+		$this->untransformedTypes = array_filter($this->parameters, function ($item) {
187
+			return $this->isPhoneType($item);
188
+		});
189
+
190
+		// Transform valid types to their namespaced class constant.
191
+		$this->allowedTypes = array_map(function ($item) {
192
+			return constant($this->constructPhoneTypeConstant($item));
193
+		}, $this->untransformedTypes);
194
+
195
+		// Add in the unsure number type if applicable.
196
+		if (array_intersect(['FIXED_LINE', 'MOBILE'], $this->parameters)) {
197
+			$this->allowedTypes[] = PhoneNumberType::FIXED_LINE_OR_MOBILE;
198
+		}
199
+	}
200
+
201
+	/**
202
+	 * Checks for parameter leftovers to force developers to write proper code.
203
+	 *
204
+	 * @throws \Propaganistas\LaravelPhone\Exceptions\InvalidParameterException
205
+	 */
206
+	protected function checkLeftoverParameters()
207
+	{
208
+		// Remove the automatic detection option if applicable.
209
+		$leftovers = array_diff($this->parameters, $this->allowedCountries, $this->untransformedTypes, array('AUTO'));
210
+		if (!empty($leftovers)) {
211
+			throw new InvalidParameterException(implode(', ', $leftovers));
212
+		}
213
+	}
214 214
 
215 215
 }
Please login to merge, or discard this patch.