/** * Factory method to create an appropriate type * * @param FormField $field * @param $submittedData * @return SpecialEmailValidator * @throws FormFieldException */ public static function create(FormField $field, $submittedData) { switch ($field->getType()) { case 'email': $object = new SpecialEmailValidator($field, $submittedData); break; default: throw FormFieldException::noSuchType($field->getType()); break; } return $object; }
/** * @param string type * @param $node * @return FormField */ public function fieldFactory($type, $node) { // Instantiate a field object $field = new FormField(strtolower($type)); // Get predifined attributes like id $attributes = $this->transpileAttributes($node->getNode(0), ['type', 'name', 'value']); $field->setAttributes($attributes); // Pattern validation callback if (array_key_exists('pattern', $attributes)) { $pattern = $attributes['pattern']; $field->setValidationCallback(function ($value) use($pattern, $field) { $validationResult = preg_match('/' . $pattern . '/', $value); if ($validationResult) { return false; // it's valid! } return true; }); } // Add value $field->setDefault($node->attr('value'))->setName(str_replace('\\"', '', $node->attr('name'))); // Set madatory if required if (array_key_exists('required', $attributes)) { $field->setMandatory(true); } return $field; }
/** * Add CSRF token hidden input field */ private function addCSRFTokenField() { $this->nonceValue = $this->createNonce(); $nonce = new FormField(FormField::TYPE_HIDDEN); $nonce->setName('nonce')->setValue($this->createNonce())->setValidationCallback(function ($value) { if (function_exists('wp_verify_nonce')) { if (!wp_verify_nonce($value, $this->nonceKey)) { throw new \Exception('Unauthorized request'); } } else { if (!isset($_SESSION['csrf_tokens'][$value])) { throw new \Exception('Unauthorized request'); } else { unset($_SESSION['csrf_tokens'][$value]); } } return false; })->setMandatory(true); $key = 'nonce'; $this->addField($key, $nonce); }