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\HttpFoundation;
14 use Symfony\Component\HttpFoundation\File\UploadedFile;
17 * FileBag is a container for uploaded files.
19 * @author Fabien Potencier <fabien@symfony.com>
20 * @author Bulat Shakirzyanov <mallluhuct@gmail.com>
22 class FileBag extends ParameterBag
24 private static $fileKeys = array('error', 'name', 'size', 'tmp_name', 'type');
29 * @param array $parameters An array of HTTP files
31 public function __construct(array $parameters = array())
33 $this->replace($parameters);
39 public function replace(array $files = array())
41 $this->parameters = array();
48 public function set($key, $value)
50 if (!is_array($value) && !$value instanceof UploadedFile) {
51 throw new \InvalidArgumentException('An uploaded file must be an array or an instance of UploadedFile.');
54 parent::set($key, $this->convertFileInformation($value));
60 public function add(array $files = array())
62 foreach ($files as $key => $file) {
63 $this->set($key, $file);
68 * Converts uploaded files to UploadedFile instances.
70 * @param array|UploadedFile $file A (multi-dimensional) array of uploaded file information
72 * @return UploadedFile|UploadedFile[] A (multi-dimensional) array of UploadedFile instances
74 protected function convertFileInformation($file)
76 if ($file instanceof UploadedFile) {
80 $file = $this->fixPhpFilesArray($file);
81 if (is_array($file)) {
82 $keys = array_keys($file);
85 if ($keys == self::$fileKeys) {
86 if (UPLOAD_ERR_NO_FILE == $file['error']) {
89 $file = new UploadedFile($file['tmp_name'], $file['name'], $file['type'], $file['size'], $file['error']);
92 $file = array_map(array($this, 'convertFileInformation'), $file);
100 * Fixes a malformed PHP $_FILES array.
102 * PHP has a bug that the format of the $_FILES array differs, depending on
103 * whether the uploaded file fields had normal field names or array-like
104 * field names ("normal" vs. "parent[child]").
106 * This method fixes the array to look like the "normal" $_FILES array.
108 * It's safe to pass an already converted array, in which case this method
109 * just returns the original array unmodified.
115 protected function fixPhpFilesArray($data)
117 if (!is_array($data)) {
121 $keys = array_keys($data);
124 if (self::$fileKeys != $keys || !isset($data['name']) || !is_array($data['name'])) {
129 foreach (self::$fileKeys as $k) {
133 foreach ($data['name'] as $key => $name) {
134 $files[$key] = $this->fixPhpFilesArray(array(
135 'error' => $data['error'][$key],
137 'type' => $data['type'][$key],
138 'tmp_name' => $data['tmp_name'][$key],
139 'size' => $data['size'][$key],