@@ -158,6 +158,11 @@ public function setCardReference($value)
158
158
return $ this ->setParameter ('cardReference ' , $ value );
159
159
}
160
160
161
+ /**
162
+ * @throws InvalidRequestException on any validation failure.
163
+ * @return string The amount formatted to the correct number of decimal places for the selected currency.
164
+ */
165
+
161
166
public function getAmount ()
162
167
{
163
168
$ amount = $ this ->getParameter ('amount ' );
@@ -172,13 +177,13 @@ public function getAmount()
172
177
}
173
178
174
179
if (is_string ($ amount )) {
175
- // A '-' is not considered a valid character, so a negative amounts will be invalid .
176
- if (preg_match ('/[^0-9\.]/ ' , $ amount )) {
180
+ // Negative amounts are valid numbers at this stage .
181
+ if (preg_match ('/[^0-9\.- ]/ ' , $ amount )) {
177
182
throw new InvalidRequestException ('Invalid character in amount. ' );
178
183
}
179
184
180
- // Generic number, with optional decimals.
181
- if (!preg_match ('/^[0-9]+(\.[0-9]*)?$/ ' , $ amount )) {
185
+ // Generic number, with optional sign and decimals.
186
+ if (!preg_match ('/^[-]?[ 0-9]+(\.[0-9]*)?$/ ' , $ amount )) {
182
187
throw new InvalidRequestException ('Amount string is not a valid decimal number. ' );
183
188
}
184
189
@@ -191,11 +196,15 @@ public function getAmount()
191
196
// The number_format() used later requires a float.
192
197
$ amount = (float )$ amount ;
193
198
194
- // Check for rounding that may occur if too many decimal places are supplied.
199
+ // Check for a negative amount.
200
+ if ($ amount < 0 ) {
201
+ throw new InvalidRequestException ('A negative amount is not allowed. ' );
202
+ }
203
+
204
+ // Check for rounding that may occur if too many significant decimal digits are supplied.
195
205
$ decimal_count = strlen (substr (strrchr ((string )$ amount , '. ' ), 1 ));
196
206
if ($ decimal_count > $ this ->getCurrencyDecimalPlaces ()) {
197
207
throw new InvalidRequestException ('Amount precision is too high for currency. ' );
198
-
199
208
}
200
209
201
210
return $ this ->formatCurrency ($ amount );
0 commit comments