Form.php 15 KB

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