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');
27 * @param array $parameters An array of HTTP files
29 public function __construct(array $parameters = array())
31 $this->replace($parameters);
37 public function replace(array $files = array())
39 $this->parameters = array();
46 public function set($key, $value)
48 if (!is_array($value) && !$value instanceof UploadedFile) {
49 throw new \InvalidArgumentException('An uploaded file must be an array or an instance of UploadedFile.');
52 parent::set($key, $this->convertFileInformation($value));
58 public function add(array $files = array())
60 foreach ($files as $key => $file) {
61 $this->set($key, $file);
66 * Converts uploaded files to UploadedFile instances.
68 * @param array|UploadedFile $file A (multi-dimensional) array of uploaded file information
70 * @return UploadedFile[]|UploadedFile|null A (multi-dimensional) array of UploadedFile instances
72 protected function convertFileInformation($file)
74 if ($file instanceof UploadedFile) {
78 $file = $this->fixPhpFilesArray($file);
79 if (is_array($file)) {
80 $keys = array_keys($file);
83 if ($keys == self::$fileKeys) {
84 if (UPLOAD_ERR_NO_FILE == $file['error']) {
87 $file = new UploadedFile($file['tmp_name'], $file['name'], $file['type'], $file['size'], $file['error']);
90 $file = array_map(array($this, 'convertFileInformation'), $file);
91 if (array_keys($keys) === $keys) {
92 $file = array_filter($file);
101 * Fixes a malformed PHP $_FILES array.
103 * PHP has a bug that the format of the $_FILES array differs, depending on
104 * whether the uploaded file fields had normal field names or array-like
105 * field names ("normal" vs. "parent[child]").
107 * This method fixes the array to look like the "normal" $_FILES array.
109 * It's safe to pass an already converted array, in which case this method
110 * just returns the original array unmodified.
114 protected function fixPhpFilesArray($data)
116 if (!is_array($data)) {
120 $keys = array_keys($data);
123 if (self::$fileKeys != $keys || !isset($data['name']) || !is_array($data['name'])) {
128 foreach (self::$fileKeys as $k) {
132 foreach ($data['name'] as $key => $name) {
133 $files[$key] = $this->fixPhpFilesArray(array(
134 'error' => $data['error'][$key],
136 'type' => $data['type'][$key],
137 'tmp_name' => $data['tmp_name'][$key],
138 'size' => $data['size'][$key],