silverstripe-framework/src/Forms/CreditCardField.php

122 lines
2.9 KiB
PHP
Raw Normal View History

<?php
namespace SilverStripe\Forms;
/**
2012-06-26 15:03:11 +02:00
* Allows input of credit card numbers via four separate form fields,
* including generic validation of its numeric values.
2014-08-15 08:53:05 +02:00
*
2012-06-26 15:03:11 +02:00
* @todo Validate
*/
2016-11-29 00:31:16 +01:00
class CreditCardField extends TextField
{
2016-11-29 00:31:16 +01:00
/**
* Add default attributes for use on all inputs.
*
* @return array List of attributes
*/
public function getAttributes()
{
return array_merge(
parent::getAttributes(),
array(
'autocomplete' => 'off',
'maxlength' => 4,
'size' => 4
)
);
}
2014-08-15 08:53:05 +02:00
2016-11-29 00:31:16 +01:00
public function Field($properties = array())
{
$parts = $this->arrayValue();
2016-11-29 00:31:16 +01:00
$properties['ValueOne'] = $parts[0];
$properties['ValueTwo'] = $parts[1];
$properties['ValueThree'] = $parts[2];
$properties['ValueFour'] = $parts[3];
2013-09-30 17:48:15 +02:00
2016-11-29 00:31:16 +01:00
return parent::Field($properties);
}
2016-11-29 00:31:16 +01:00
/**
* Get tabindex HTML string
*
* @param int $increment Increase current tabindex by this value
* @return string
*/
public function getTabIndexHTML($increment = 0)
{
// we can't add a tabindex if there hasn't been one set yet.
if ($this->getAttribute('tabindex') === null) {
return false;
}
2016-11-29 00:31:16 +01:00
$tabIndex = (int)$this->getAttribute('tabindex') + (int)$increment;
return (is_numeric($tabIndex)) ? ' tabindex = "' . $tabIndex . '"' : '';
}
2016-11-29 00:31:16 +01:00
public function dataValue()
{
if (is_array($this->value)) {
return implode("", $this->value);
} else {
return $this->value;
}
}
2016-11-29 00:31:16 +01:00
/**
* Get either list of values, or null
*
* @return array
*/
public function arrayValue()
{
if (is_array($this->value)) {
return $this->value;
}
2016-11-29 00:31:16 +01:00
$value = $this->dataValue();
return $this->parseCreditCard($value);
}
2016-11-29 00:31:16 +01:00
/**
* Parse credit card value into list of four four-digit values
*
* @param string $value
* @return array|null
*/
protected function parseCreditCard($value)
{
if (preg_match("/([0-9]{4})([0-9]{4})([0-9]{4})([0-9]{4})/", $value, $parts)) {
return [ $parts[1], $parts[2], $parts[3], $parts[4] ];
}
return null;
}
2014-08-15 08:53:05 +02:00
2016-11-29 00:31:16 +01:00
public function validate($validator)
{
$value = $this->dataValue();
if (empty($value)) {
return true;
}
2014-08-15 08:53:05 +02:00
2016-11-29 00:31:16 +01:00
// Check if format is valid
if ($this->parseCreditCard($value)) {
return true;
}
2016-11-29 00:31:16 +01:00
// Format is invalid
$validator->validationError(
$this->name,
_t(
'Form.VALIDATIONCREDIT',
"Please ensure you have entered the credit card number correctly"
),
"validation"
);
return false;
}
}