Drupal investigation

Form.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\DomCrawler;
  11. use Symfony\Component\DomCrawler\Field\ChoiceFormField;
  12. use Symfony\Component\DomCrawler\Field\FormField;
  13. /**
  14. * Form represents an HTML form.
  15. *
  16. * @author Fabien Potencier <fabien@symfony.com>
  17. */
  18. class Form extends Link implements \ArrayAccess
  19. {
  20. /**
  21. * @var \DOMElement
  22. */
  23. private $button;
  24. /**
  25. * @var FormFieldRegistry
  26. */
  27. private $fields;
  28. /**
  29. * @var string
  30. */
  31. private $baseHref;
  32. /**
  33. * Constructor.
  34. *
  35. * @param \DOMElement $node A \DOMElement instance
  36. * @param string $currentUri The URI of the page where the form is embedded
  37. * @param string $method The method to use for the link (if null, it defaults to the method defined by the form)
  38. * @param string $baseHref The URI of the <base> used for relative links, but not for empty action
  39. *
  40. * @throws \LogicException if the node is not a button inside a form tag
  41. */
  42. public function __construct(\DOMElement $node, $currentUri, $method = null, $baseHref = null)
  43. {
  44. parent::__construct($node, $currentUri, $method);
  45. $this->baseHref = $baseHref;
  46. $this->initialize();
  47. }
  48. /**
  49. * Gets the form node associated with this form.
  50. *
  51. * @return \DOMElement A \DOMElement instance
  52. */
  53. public function getFormNode()
  54. {
  55. return $this->node;
  56. }
  57. /**
  58. * Sets the value of the fields.
  59. *
  60. * @param array $values An array of field values
  61. *
  62. * @return $this
  63. */
  64. public function setValues(array $values)
  65. {
  66. foreach ($values as $name => $value) {
  67. $this->fields->set($name, $value);
  68. }
  69. return $this;
  70. }
  71. /**
  72. * Gets the field values.
  73. *
  74. * The returned array does not include file fields (@see getFiles).
  75. *
  76. * @return array An array of field values
  77. */
  78. public function getValues()
  79. {
  80. $values = array();
  81. foreach ($this->fields->all() as $name => $field) {
  82. if ($field->isDisabled()) {
  83. continue;
  84. }
  85. if (!$field instanceof Field\FileFormField && $field->hasValue()) {
  86. $values[$name] = $field->getValue();
  87. }
  88. }
  89. return $values;
  90. }
  91. /**
  92. * Gets the file field values.
  93. *
  94. * @return array An array of file field values
  95. */
  96. public function getFiles()
  97. {
  98. if (!in_array($this->getMethod(), array('POST', 'PUT', 'DELETE', 'PATCH'))) {
  99. return array();
  100. }
  101. $files = array();
  102. foreach ($this->fields->all() as $name => $field) {
  103. if ($field->isDisabled()) {
  104. continue;
  105. }
  106. if ($field instanceof Field\FileFormField) {
  107. $files[$name] = $field->getValue();
  108. }
  109. }
  110. return $files;
  111. }
  112. /**
  113. * Gets the field values as PHP.
  114. *
  115. * This method converts fields with the array notation
  116. * (like foo[bar] to arrays) like PHP does.
  117. *
  118. * @return array An array of field values
  119. */
  120. public function getPhpValues()
  121. {
  122. $values = array();
  123. foreach ($this->getValues() as $name => $value) {
  124. $qs = http_build_query(array($name => $value), '', '&');
  125. if (!empty($qs)) {
  126. parse_str($qs, $expandedValue);
  127. $varName = substr($name, 0, strlen(key($expandedValue)));
  128. $values = array_replace_recursive($values, array($varName => current($expandedValue)));
  129. }
  130. }
  131. return $values;
  132. }
  133. /**
  134. * Gets the file field values as PHP.
  135. *
  136. * This method converts fields with the array notation
  137. * (like foo[bar] to arrays) like PHP does.
  138. * The returned array is consistent with the array for field values
  139. * (@see getPhpValues), rather than uploaded files found in $_FILES.
  140. * For a compound file field foo[bar] it will create foo[bar][name],
  141. * instead of foo[name][bar] which would be found in $_FILES.
  142. *
  143. * @return array An array of file field values
  144. */
  145. public function getPhpFiles()
  146. {
  147. $values = array();
  148. foreach ($this->getFiles() as $name => $value) {
  149. $qs = http_build_query(array($name => $value), '', '&');
  150. if (!empty($qs)) {
  151. parse_str($qs, $expandedValue);
  152. $varName = substr($name, 0, strlen(key($expandedValue)));
  153. $values = array_replace_recursive($values, array($varName => current($expandedValue)));
  154. }
  155. }
  156. return $values;
  157. }
  158. /**
  159. * Gets the URI of the form.
  160. *
  161. * The returned URI is not the same as the form "action" attribute.
  162. * This method merges the value if the method is GET to mimics
  163. * browser behavior.
  164. *
  165. * @return string The URI
  166. */
  167. public function getUri()
  168. {
  169. $uri = parent::getUri();
  170. if (!in_array($this->getMethod(), array('POST', 'PUT', 'DELETE', 'PATCH'))) {
  171. $query = parse_url($uri, PHP_URL_QUERY);
  172. $currentParameters = array();
  173. if ($query) {
  174. parse_str($query, $currentParameters);
  175. }
  176. $queryString = http_build_query(array_merge($currentParameters, $this->getValues()), null, '&');
  177. $pos = strpos($uri, '?');
  178. $base = false === $pos ? $uri : substr($uri, 0, $pos);
  179. $uri = rtrim($base.'?'.$queryString, '?');
  180. }
  181. return $uri;
  182. }
  183. protected function getRawUri()
  184. {
  185. return $this->node->getAttribute('action');
  186. }
  187. /**
  188. * Gets the form method.
  189. *
  190. * If no method is defined in the form, GET is returned.
  191. *
  192. * @return string The method
  193. */
  194. public function getMethod()
  195. {
  196. if (null !== $this->method) {
  197. return $this->method;
  198. }
  199. return $this->node->getAttribute('method') ? strtoupper($this->node->getAttribute('method')) : 'GET';
  200. }
  201. /**
  202. * Returns true if the named field exists.
  203. *
  204. * @param string $name The field name
  205. *
  206. * @return bool true if the field exists, false otherwise
  207. */
  208. public function has($name)
  209. {
  210. return $this->fields->has($name);
  211. }
  212. /**
  213. * Removes a field from the form.
  214. *
  215. * @param string $name The field name
  216. */
  217. public function remove($name)
  218. {
  219. $this->fields->remove($name);
  220. }
  221. /**
  222. * Gets a named field.
  223. *
  224. * @param string $name The field name
  225. *
  226. * @return FormField The field instance
  227. *
  228. * @throws \InvalidArgumentException When field is not present in this form
  229. */
  230. public function get($name)
  231. {
  232. return $this->fields->get($name);
  233. }
  234. /**
  235. * Sets a named field.
  236. *
  237. * @param FormField $field The field
  238. */
  239. public function set(FormField $field)
  240. {
  241. $this->fields->add($field);
  242. }
  243. /**
  244. * Gets all fields.
  245. *
  246. * @return FormField[]
  247. */
  248. public function all()
  249. {
  250. return $this->fields->all();
  251. }
  252. /**
  253. * Returns true if the named field exists.
  254. *
  255. * @param string $name The field name
  256. *
  257. * @return bool true if the field exists, false otherwise
  258. */
  259. public function offsetExists($name)
  260. {
  261. return $this->has($name);
  262. }
  263. /**
  264. * Gets the value of a field.
  265. *
  266. * @param string $name The field name
  267. *
  268. * @return FormField The associated Field instance
  269. *
  270. * @throws \InvalidArgumentException if the field does not exist
  271. */
  272. public function offsetGet($name)
  273. {
  274. return $this->fields->get($name);
  275. }
  276. /**
  277. * Sets the value of a field.
  278. *
  279. * @param string $name The field name
  280. * @param string|array $value The value of the field
  281. *
  282. * @throws \InvalidArgumentException if the field does not exist
  283. */
  284. public function offsetSet($name, $value)
  285. {
  286. $this->fields->set($name, $value);
  287. }
  288. /**
  289. * Removes a field from the form.
  290. *
  291. * @param string $name The field name
  292. */
  293. public function offsetUnset($name)
  294. {
  295. $this->fields->remove($name);
  296. }
  297. /**
  298. * Disables validation.
  299. *
  300. * @return self
  301. */
  302. public function disableValidation()
  303. {
  304. foreach ($this->fields->all() as $field) {
  305. if ($field instanceof Field\ChoiceFormField) {
  306. $field->disableValidation();
  307. }
  308. }
  309. return $this;
  310. }
  311. /**
  312. * Sets the node for the form.
  313. *
  314. * Expects a 'submit' button \DOMElement and finds the corresponding form element, or the form element itself.
  315. *
  316. * @param \DOMElement $node A \DOMElement instance
  317. *
  318. * @throws \LogicException If given node is not a button or input or does not have a form ancestor
  319. */
  320. protected function setNode(\DOMElement $node)
  321. {
  322. $this->button = $node;
  323. if ('button' === $node->nodeName || ('input' === $node->nodeName && in_array(strtolower($node->getAttribute('type')), array('submit', 'button', 'image')))) {
  324. if ($node->hasAttribute('form')) {
  325. // if the node has the HTML5-compliant 'form' attribute, use it
  326. $formId = $node->getAttribute('form');
  327. $form = $node->ownerDocument->getElementById($formId);
  328. if (null === $form) {
  329. throw new \LogicException(sprintf('The selected node has an invalid form attribute (%s).', $formId));
  330. }
  331. $this->node = $form;
  332. return;
  333. }
  334. // we loop until we find a form ancestor
  335. do {
  336. if (null === $node = $node->parentNode) {
  337. throw new \LogicException('The selected node does not have a form ancestor.');
  338. }
  339. } while ('form' !== $node->nodeName);
  340. } elseif ('form' !== $node->nodeName) {
  341. throw new \LogicException(sprintf('Unable to submit on a "%s" tag.', $node->nodeName));
  342. }
  343. $this->node = $node;
  344. }
  345. /**
  346. * Adds form elements related to this form.
  347. *
  348. * Creates an internal copy of the submitted 'button' element and
  349. * the form node or the entire document depending on whether we need
  350. * to find non-descendant elements through HTML5 'form' attribute.
  351. */
  352. private function initialize()
  353. {
  354. $this->fields = new FormFieldRegistry();
  355. $xpath = new \DOMXPath($this->node->ownerDocument);
  356. // add submitted button if it has a valid name
  357. if ('form' !== $this->button->nodeName && $this->button->hasAttribute('name') && $this->button->getAttribute('name')) {
  358. if ('input' == $this->button->nodeName && 'image' == strtolower($this->button->getAttribute('type'))) {
  359. $name = $this->button->getAttribute('name');
  360. $this->button->setAttribute('value', '0');
  361. // temporarily change the name of the input node for the x coordinate
  362. $this->button->setAttribute('name', $name.'.x');
  363. $this->set(new Field\InputFormField($this->button));
  364. // temporarily change the name of the input node for the y coordinate
  365. $this->button->setAttribute('name', $name.'.y');
  366. $this->set(new Field\InputFormField($this->button));
  367. // restore the original name of the input node
  368. $this->button->setAttribute('name', $name);
  369. } else {
  370. $this->set(new Field\InputFormField($this->button));
  371. }
  372. }
  373. // find form elements corresponding to the current form
  374. if ($this->node->hasAttribute('id')) {
  375. // corresponding elements are either descendants or have a matching HTML5 form attribute
  376. $formId = Crawler::xpathLiteral($this->node->getAttribute('id'));
  377. $fieldNodes = $xpath->query(sprintf('descendant::input[@form=%s] | descendant::button[@form=%s] | descendant::textarea[@form=%s] | descendant::select[@form=%s] | //form[@id=%s]//input[not(@form)] | //form[@id=%s]//button[not(@form)] | //form[@id=%s]//textarea[not(@form)] | //form[@id=%s]//select[not(@form)]', $formId, $formId, $formId, $formId, $formId, $formId, $formId, $formId));
  378. foreach ($fieldNodes as $node) {
  379. $this->addField($node);
  380. }
  381. } else {
  382. // do the xpath query with $this->node as the context node, to only find descendant elements
  383. // however, descendant elements with form attribute are not part of this form
  384. $fieldNodes = $xpath->query('descendant::input[not(@form)] | descendant::button[not(@form)] | descendant::textarea[not(@form)] | descendant::select[not(@form)]', $this->node);
  385. foreach ($fieldNodes as $node) {
  386. $this->addField($node);
  387. }
  388. }
  389. if ($this->baseHref && '' !== $this->node->getAttribute('action')) {
  390. $this->currentUri = $this->baseHref;
  391. }
  392. }
  393. private function addField(\DOMElement $node)
  394. {
  395. if (!$node->hasAttribute('name') || !$node->getAttribute('name')) {
  396. return;
  397. }
  398. $nodeName = $node->nodeName;
  399. if ('select' == $nodeName || 'input' == $nodeName && 'checkbox' == strtolower($node->getAttribute('type'))) {
  400. $this->set(new Field\ChoiceFormField($node));
  401. } elseif ('input' == $nodeName && 'radio' == strtolower($node->getAttribute('type'))) {
  402. // there may be other fields with the same name that are no choice
  403. // fields already registered (see https://github.com/symfony/symfony/issues/11689)
  404. if ($this->has($node->getAttribute('name')) && $this->get($node->getAttribute('name')) instanceof ChoiceFormField) {
  405. $this->get($node->getAttribute('name'))->addChoice($node);
  406. } else {
  407. $this->set(new Field\ChoiceFormField($node));
  408. }
  409. } elseif ('input' == $nodeName && 'file' == strtolower($node->getAttribute('type'))) {
  410. $this->set(new Field\FileFormField($node));
  411. } elseif ('input' == $nodeName && !in_array(strtolower($node->getAttribute('type')), array('submit', 'button', 'image'))) {
  412. $this->set(new Field\InputFormField($node));
  413. } elseif ('textarea' == $nodeName) {
  414. $this->set(new Field\TextareaFormField($node));
  415. }
  416. }
  417. }