Skip to content

Commit d1341fc

Browse files
author
Andy Coates
committed
Filter characters from basket not allowed by SagePay
1 parent 93e72bb commit d1341fc

File tree

1 file changed

+42
-2
lines changed

1 file changed

+42
-2
lines changed

src/Message/AbstractRequest.php

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,46 @@ protected function createResponse($data)
144144
return $this->response = new Response($this, $data);
145145
}
146146

147+
/**
148+
* Filters out any characters that SagePay does not support from the item name.
149+
*
150+
* Believe it or not, SagePay actually have separate rules for allowed characters
151+
* for item names and discount names, hence the need for two separate methods.
152+
*
153+
* @param string $name
154+
*
155+
* @return string
156+
*/
157+
protected function filterItemName($name)
158+
{
159+
$standardChars = "0-9a-zA-Z";
160+
$allowedSpecialChars = " +'/\\&:,.-{}";
161+
$pattern = '`[^'.$standardChars.preg_quote($allowedSpecialChars, '/').']`';
162+
$name = trim(preg_replace($pattern, '', $name));
163+
164+
return $name;
165+
}
166+
167+
/**
168+
* Filters out any characters that SagePay does not support from the discount name.
169+
*
170+
* Believe it or not, SagePay actually have separate rules for allowed characters
171+
* for item names and discount names, hence the need for two separate methods.
172+
*
173+
* @param string $name
174+
*
175+
* @return string
176+
*/
177+
protected function filterDiscountName($name)
178+
{
179+
$standardChars = "0-9a-zA-Z";
180+
$allowedSpecialChars = " +'/\\:,.-{};_@()^\"~[]$=!#?|";
181+
$pattern = '`[^'.$standardChars.preg_quote($allowedSpecialChars, '/').']`';
182+
$name = trim(preg_replace($pattern, '', $name));
183+
184+
return $name;
185+
}
186+
147187
/**
148188
* Get an XML representation of the current cart items
149189
*
@@ -168,7 +208,7 @@ protected function getItemData()
168208
} else {
169209
$total = ($basketItem->getQuantity() * $basketItem->getPrice());
170210
$item = $xml->addChild('item');
171-
$item->description = $basketItem->getName();
211+
$item->description = $this->filterItemName($basketItem->getName());
172212
$item->addChild('quantity', $basketItem->getQuantity());
173213
$item->addChild('unitNetAmount', $basketItem->getPrice());
174214
$item->addChild('unitTaxAmount', '0.00');
@@ -182,7 +222,7 @@ protected function getItemData()
182222
if ($discountItem->getPrice() < 0) {
183223
$discount = $discounts->addChild('discount');
184224
$discount->addChild('fixed', ($discountItem->getPrice() * $discountItem->getQuantity()) * -1);
185-
$discount->description = $discountItem->getName();
225+
$discount->description = $this->filterDiscountName($discountItem->getName());
186226
}
187227
}
188228
}

0 commit comments

Comments
 (0)