Last active
August 5, 2016 06:20
-
-
Save samundra/1319bcaf6be4aff59dff2a0ffc96f22c to your computer and use it in GitHub Desktop.
Parses the content, search for the form and assign respective elements to array keys as `formAction`, 'formId', 'formMethod' that can be checked against for easy assertions. When multiple forms are found they will be stored on arrays with key 'availableForms'.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Parses the content, search for the form and assign respective elements to | |
| * array keys as 'formAction', 'formId', 'formMethod' that can be checked against | |
| * for easy assertions. When multiple forms are found they will be stored on | |
| * arrays with key 'availableForms'. | |
| * | |
| * @param string $content HTML content for the form | |
| * | |
| * @return array respective form attribute associations keys | |
| */ | |
| public static function extractFormInformation(string $content) : array | |
| { | |
| $dom = new DOMDocument('1.0', 'utf-8'); | |
| // Reports error on HTML5 tags so temporarily suppress error to load DOM | |
| libxml_use_internal_errors(true); | |
| $dom->loadHTML($content); | |
| libxml_use_internal_errors(false); | |
| $forms = $dom->getElementsByTagName('form'); | |
| // array of minimal available attributes in the form | |
| $attrFilters = [ | |
| 'action', 'id', 'method', 'name', 'class' | |
| ]; | |
| $availableForms = []; | |
| foreach ($forms as $idx => $formElement) { | |
| foreach ($formElement->attributes as $attr) { | |
| if (in_array($attr->nodeName, $attrFilters)) { | |
| $variable = 'form' . studly_case($attr->nodeName); | |
| $availableForms[$idx][$variable] = $attr->nodeValue; | |
| } | |
| } | |
| } | |
| array_walk($attrFilters, function (&$value) { | |
| $value = 'form' . ucfirst($value); | |
| }); | |
| return compact($attrFilters, 'availableForms'); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment