4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\DomCrawler\Field;
15 * FileFormField represents a file form field (an HTML file input tag).
17 * @author Fabien Potencier <fabien@symfony.com>
19 class FileFormField extends FormField
22 * Sets the PHP error code associated with the field.
24 * @param int $error The error code (one of UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE, UPLOAD_ERR_PARTIAL, UPLOAD_ERR_NO_FILE, UPLOAD_ERR_NO_TMP_DIR, UPLOAD_ERR_CANT_WRITE, or UPLOAD_ERR_EXTENSION)
26 * @throws \InvalidArgumentException When error code doesn't exist
28 public function setErrorCode($error)
30 $codes = array(UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE, UPLOAD_ERR_PARTIAL, UPLOAD_ERR_NO_FILE, UPLOAD_ERR_NO_TMP_DIR, UPLOAD_ERR_CANT_WRITE, UPLOAD_ERR_EXTENSION);
31 if (!\in_array($error, $codes)) {
32 throw new \InvalidArgumentException(sprintf('The error code %s is not valid.', $error));
35 $this->value = array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => $error, 'size' => 0);
39 * Sets the value of the field.
41 * @param string $value The value of the field
43 public function upload($value)
45 $this->setValue($value);
49 * Sets the value of the field.
51 * @param string $value The value of the field
53 public function setValue($value)
55 if (null !== $value && is_readable($value)) {
56 $error = UPLOAD_ERR_OK;
57 $size = filesize($value);
58 $info = pathinfo($value);
59 $name = $info['basename'];
61 // copy to a tmp location
62 $tmp = sys_get_temp_dir().'/'.strtr(substr(base64_encode(hash('sha256', uniqid(mt_rand(), true), true)), 0, 7), '/', '_');
63 if (array_key_exists('extension', $info)) {
64 $tmp .= '.'.$info['extension'];
72 $error = UPLOAD_ERR_NO_FILE;
78 $this->value = array('name' => $name, 'type' => '', 'tmp_name' => $value, 'error' => $error, 'size' => $size);
82 * Sets path to the file as string for simulating HTTP request.
84 * @param string $path The path to the file
86 public function setFilePath($path)
88 parent::setValue($path);
92 * Initializes the form field.
94 * @throws \LogicException When node type is incorrect
96 protected function initialize()
98 if ('input' !== $this->node->nodeName) {
99 throw new \LogicException(sprintf('A FileFormField can only be created from an input tag (%s given).', $this->node->nodeName));
102 if ('file' !== strtolower($this->node->getAttribute('type'))) {
103 throw new \LogicException(sprintf('A FileFormField can only be created from an input tag with a type of file (given type is %s).', $this->node->getAttribute('type')));
106 $this->setValue(null);