Form.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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\FormField;
  12. /**
  13. * Form represents an HTML form.
  14. *
  15. * @author Fabien Potencier <fabien@symfony.com>
  16. *
  17. * @api
  18. */
  19. class Form extends Link implements \ArrayAccess
  20. {
  21. /**
  22. * @var \DOMNode
  23. */
  24. private $button;
  25. /**
  26. * @var Field\FormField[]
  27. */
  28. private $fields;
  29. /**
  30. * Constructor.
  31. *
  32. * @param \DOMNode $node A \DOMNode instance
  33. * @param string $currentUri The URI of the page where the form is embedded
  34. * @param string $method The method to use for the link (if null, it defaults to the method defined by the form)
  35. *
  36. * @throws \LogicException if the node is not a button inside a form tag
  37. *
  38. * @api
  39. */
  40. public function __construct(\DOMNode $node, $currentUri, $method = null)
  41. {
  42. parent::__construct($node, $currentUri, $method);
  43. $this->initialize();
  44. }
  45. /**
  46. * Gets the form node associated with this form.
  47. *
  48. * @return \DOMNode A \DOMNode instance
  49. */
  50. public function getFormNode()
  51. {
  52. return $this->node;
  53. }
  54. /**
  55. * Sets the value of the fields.
  56. *
  57. * @param array $values An array of field values
  58. *
  59. * @return Form
  60. *
  61. * @api
  62. */
  63. public function setValues(array $values)
  64. {
  65. foreach ($values as $name => $value) {
  66. $this->fields->set($name, $value);
  67. }
  68. return $this;
  69. }
  70. /**
  71. * Gets the field values.
  72. *
  73. * The returned array does not include file fields (@see getFiles).
  74. *
  75. * @return array An array of field values.
  76. *
  77. * @api
  78. */
  79. public function getValues()
  80. {
  81. $values = array();
  82. foreach ($this->fields->all() as $name => $field) {
  83. if ($field->isDisabled()) {
  84. continue;
  85. }
  86. if (!$field instanceof Field\FileFormField && $field->hasValue()) {
  87. $values[$name] = $field->getValue();
  88. }
  89. }
  90. return $values;
  91. }
  92. /**
  93. * Gets the file field values.
  94. *
  95. * @return array An array of file field values.
  96. *
  97. * @api
  98. */
  99. public function getFiles()
  100. {
  101. if (!in_array($this->getMethod(), array('POST', 'PUT', 'DELETE', 'PATCH'))) {
  102. return array();
  103. }
  104. $files = array();
  105. foreach ($this->fields->all() as $name => $field) {
  106. if ($field->isDisabled()) {
  107. continue;
  108. }
  109. if ($field instanceof Field\FileFormField) {
  110. $files[$name] = $field->getValue();
  111. }
  112. }
  113. return $files;
  114. }
  115. /**
  116. * Gets the field values as PHP.
  117. *
  118. * This method converts fields with the array notation
  119. * (like foo[bar] to arrays) like PHP does.
  120. *
  121. * @return array An array of field values.
  122. *
  123. * @api
  124. */
  125. public function getPhpValues()
  126. {
  127. $qs = http_build_query($this->getValues(), '', '&');
  128. parse_str($qs, $values);
  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. *
  137. * @return array An array of field values.
  138. *
  139. * @api
  140. */
  141. public function getPhpFiles()
  142. {
  143. $qs = http_build_query($this->getFiles(), '', '&');
  144. parse_str($qs, $values);
  145. return $values;
  146. }
  147. /**
  148. * Gets the URI of the form.
  149. *
  150. * The returned URI is not the same as the form "action" attribute.
  151. * This method merges the value if the method is GET to mimics
  152. * browser behavior.
  153. *
  154. * @return string The URI
  155. *
  156. * @api
  157. */
  158. public function getUri()
  159. {
  160. $uri = parent::getUri();
  161. if (!in_array($this->getMethod(), array('POST', 'PUT', 'DELETE', 'PATCH')) && $queryString = http_build_query($this->getValues(), null, '&')) {
  162. $sep = false === strpos($uri, '?') ? '?' : '&';
  163. $uri .= $sep.$queryString;
  164. }
  165. return $uri;
  166. }
  167. protected function getRawUri()
  168. {
  169. return $this->node->getAttribute('action');
  170. }
  171. /**
  172. * Gets the form method.
  173. *
  174. * If no method is defined in the form, GET is returned.
  175. *
  176. * @return string The method
  177. *
  178. * @api
  179. */
  180. public function getMethod()
  181. {
  182. if (null !== $this->method) {
  183. return $this->method;
  184. }
  185. return $this->node->getAttribute('method') ? strtoupper($this->node->getAttribute('method')) : 'GET';
  186. }
  187. /**
  188. * Returns true if the named field exists.
  189. *
  190. * @param string $name The field name
  191. *
  192. * @return Boolean true if the field exists, false otherwise
  193. *
  194. * @api
  195. */
  196. public function has($name)
  197. {
  198. return $this->fields->has($name);
  199. }
  200. /**
  201. * Removes a field from the form.
  202. *
  203. * @param string $name The field name
  204. *
  205. * @throws \InvalidArgumentException when the name is malformed
  206. *
  207. * @api
  208. */
  209. public function remove($name)
  210. {
  211. $this->fields->remove($name);
  212. }
  213. /**
  214. * Gets a named field.
  215. *
  216. * @param string $name The field name
  217. *
  218. * @return FormField The field instance
  219. *
  220. * @throws \InvalidArgumentException When field is not present in this form
  221. *
  222. * @api
  223. */
  224. public function get($name)
  225. {
  226. return $this->fields->get($name);
  227. }
  228. /**
  229. * Sets a named field.
  230. *
  231. * @param FormField $field The field
  232. *
  233. * @api
  234. */
  235. public function set(FormField $field)
  236. {
  237. $this->fields->add($field);
  238. }
  239. /**
  240. * Gets all fields.
  241. *
  242. * @return FormField[] An array of fields
  243. *
  244. * @api
  245. */
  246. public function all()
  247. {
  248. return $this->fields->all();
  249. }
  250. /**
  251. * Returns true if the named field exists.
  252. *
  253. * @param string $name The field name
  254. *
  255. * @return Boolean true if the field exists, false otherwise
  256. */
  257. public function offsetExists($name)
  258. {
  259. return $this->has($name);
  260. }
  261. /**
  262. * Gets the value of a field.
  263. *
  264. * @param string $name The field name
  265. *
  266. * @return FormField The associated Field instance
  267. *
  268. * @throws \InvalidArgumentException if the field does not exist
  269. */
  270. public function offsetGet($name)
  271. {
  272. return $this->fields->get($name);
  273. }
  274. /**
  275. * Sets the value of a field.
  276. *
  277. * @param string $name The field name
  278. * @param string|array $value The value of the field
  279. *
  280. * @throws \InvalidArgumentException if the field does not exist
  281. */
  282. public function offsetSet($name, $value)
  283. {
  284. $this->fields->set($name, $value);
  285. }
  286. /**
  287. * Removes a field from the form.
  288. *
  289. * @param string $name The field name
  290. */
  291. public function offsetUnset($name)
  292. {
  293. $this->fields->remove($name);
  294. }
  295. /**
  296. * Sets the node for the form.
  297. *
  298. * Expects a 'submit' button \DOMNode and finds the corresponding form element.
  299. *
  300. * @param \DOMNode $node A \DOMNode instance
  301. *
  302. * @throws \LogicException If given node is not a button or input or does not have a form ancestor
  303. */
  304. protected function setNode(\DOMNode $node)
  305. {
  306. $this->button = $node;
  307. if ('button' == $node->nodeName || ('input' == $node->nodeName && in_array($node->getAttribute('type'), array('submit', 'button', 'image')))) {
  308. if ($node->hasAttribute('form')) {
  309. // if the node has the HTML5-compliant 'form' attribute, use it
  310. $formId = $node->getAttribute('form');
  311. $form = $node->ownerDocument->getElementById($formId);
  312. if (null === $form) {
  313. throw new \LogicException(sprintf('The selected node has an invalid form attribute (%s).', $formId));
  314. }
  315. $this->node = $form;
  316. return;
  317. }
  318. // we loop until we find a form ancestor
  319. do {
  320. if (null === $node = $node->parentNode) {
  321. throw new \LogicException('The selected node does not have a form ancestor.');
  322. }
  323. } while ('form' != $node->nodeName);
  324. } elseif ('form' != $node->nodeName) {
  325. throw new \LogicException(sprintf('Unable to submit on a "%s" tag.', $node->nodeName));
  326. }
  327. $this->node = $node;
  328. }
  329. private function initialize()
  330. {
  331. $this->fields = new FormFieldRegistry();
  332. $document = new \DOMDocument('1.0', 'UTF-8');
  333. $node = $document->importNode($this->node, true);
  334. $button = $document->importNode($this->button, true);
  335. $root = $document->appendChild($document->createElement('_root'));
  336. $root->appendChild($node);
  337. $root->appendChild($button);
  338. $xpath = new \DOMXPath($document);
  339. // add descendant elements to the form
  340. $fieldNodes = $xpath->query('descendant::input | descendant::button | descendant::textarea | descendant::select', $root);
  341. foreach ($fieldNodes as $node) {
  342. $this->addField($node, $button);
  343. }
  344. // find form elements corresponding to the current form by the HTML5 form attribute
  345. if ($this->node->hasAttribute('id')) {
  346. $formId = Crawler::xpathLiteral($this->node->getAttribute('id'));
  347. $xpath = new \DOMXPath($this->node->ownerDocument);
  348. $fieldNodes = $xpath->query(sprintf('descendant::input[@form=%s] | descendant::button[@form=%s] | descendant::textarea[@form=%s] | descendant::select[@form=%s]', $formId, $formId, $formId, $formId));
  349. foreach ($fieldNodes as $node) {
  350. $this->addField($node, $button);
  351. }
  352. }
  353. }
  354. private function addField(\DOMNode $node, \DOMNode $button)
  355. {
  356. if (!$node->hasAttribute('name') || !$node->getAttribute('name')) {
  357. return;
  358. }
  359. $nodeName = $node->nodeName;
  360. if ($node === $button) {
  361. $this->set(new Field\InputFormField($node));
  362. } elseif ('select' == $nodeName || 'input' == $nodeName && 'checkbox' == $node->getAttribute('type')) {
  363. $this->set(new Field\ChoiceFormField($node));
  364. } elseif ('input' == $nodeName && 'radio' == $node->getAttribute('type')) {
  365. if ($this->has($node->getAttribute('name'))) {
  366. $this->get($node->getAttribute('name'))->addChoice($node);
  367. } else {
  368. $this->set(new Field\ChoiceFormField($node));
  369. }
  370. } elseif ('input' == $nodeName && 'file' == $node->getAttribute('type')) {
  371. $this->set(new Field\FileFormField($node));
  372. } elseif ('input' == $nodeName && !in_array($node->getAttribute('type'), array('submit', 'button', 'image'))) {
  373. $this->set(new Field\InputFormField($node));
  374. } elseif ('textarea' == $nodeName) {
  375. $this->set(new Field\TextareaFormField($node));
  376. }
  377. }
  378. }