Source of file EcommerceCreditCardField.php
Size: 3,124 Bytes - Last Modified: 2021-12-23T10:39:35+00:00
/var/www/docs.ssmods.com/process/src/src/Forms/Fields/EcommerceCreditCardField.php
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 | <?php namespace Sunnysideup\Ecommerce\Forms\Fields; use SilverStripe\Forms\TextField; use SilverStripe\View\Requirements; /** * Allows input of credit card numbers via four separate form fields, * including generic validation of its numeric values. * * @todo Validate */ class EcommerceCreditCardField extends TextField { /** * Add default attributes for use on all inputs. * * @return array List of attributes */ public function getAttributes() { return array_merge( parent::getAttributes(), [ 'autocomplete' => 'off', 'maxlength' => 4, 'size' => 4, ] ); } /** * renders with EcommerceCreditCardField.ss. * * @param mixed $properties */ public function Field($properties = []) { Requirements::javascript('sunnysideup/ecommerce: client/javascript/EcomCreditCardValidation.js'); $parts = $this->value; if (! is_array($parts)) { $parts = explode("\n", chunk_split($parts, 4, "\n")); } $parts = array_pad($parts, 4, ''); $properties['ValueOne'] = $parts[0]; $properties['ValueTwo'] = $parts[1]; $properties['ValueThree'] = $parts[2]; $properties['ValueFour'] = $parts[3]; return parent::Field($properties); } /** * Get tabindex HTML string. * * @param int $increment Increase current tabindex by this value * * @return bool|string */ public function getTabIndexHTML($increment = 0) { // we can't add a tabindex if there hasn't been one set yet. if (null === $this->getAttribute('tabindex')) { return false; } $tabIndex = (int) $this->getAttribute('tabindex') + (int) $increment; return is_numeric($tabIndex) ? ' tabindex = "' . $tabIndex . '"' : ''; } public function dataValue() { if (is_array($this->value)) { return implode('', $this->value); } return $this->value; } /** * checks if a credit card is a real credit card number. * * @reference: http://en.wikipedia.org/wiki/Luhn_algorithm * * @param mixed $validator */ public function validate($validator) { // If the field is empty then don't return an invalidation message $cardNumber = trim(implode('', $this->value)); if (! $cardNumber && ! $this->Required()) { return true; } for ($sum = 0, $i = strlen($cardNumber) - 1; $i >= 0; --$i) { $digit = (int) $cardNumber[$i]; $sum += ($i % 2) === 0 ? array_sum(str_split($digit * 2)) : $digit; } if (! (($sum % 10) === 0)) { $validator->validationError( $this->name, _t( 'Form.VALID_CREDIT_CARD_NUMBER', 'Please ensure you have entered a valid card number.' ), 'bad' ); return false; } return true; } } |