Skip to content

Commit 07babbf

Browse files
committed
Make checking for negative amouunts explicit.
1 parent 197c6a7 commit 07babbf

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

src/Omnipay/Common/Message/AbstractRequest.php

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,11 @@ public function setCardReference($value)
158158
return $this->setParameter('cardReference', $value);
159159
}
160160

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+
161166
public function getAmount()
162167
{
163168
$amount = $this->getParameter('amount');
@@ -172,13 +177,13 @@ public function getAmount()
172177
}
173178

174179
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)) {
177182
throw new InvalidRequestException('Invalid character in amount.');
178183
}
179184

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)) {
182187
throw new InvalidRequestException('Amount string is not a valid decimal number.');
183188
}
184189

@@ -191,11 +196,15 @@ public function getAmount()
191196
// The number_format() used later requires a float.
192197
$amount = (float)$amount;
193198

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.
195205
$decimal_count = strlen(substr(strrchr((string)$amount, '.'), 1));
196206
if ($decimal_count > $this->getCurrencyDecimalPlaces()) {
197207
throw new InvalidRequestException('Amount precision is too high for currency.');
198-
199208
}
200209

201210
return $this->formatCurrency($amount);

0 commit comments

Comments
 (0)