1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10:
11:
12: namespace Symfony\Component\HttpFoundation;
13:
14: use Symfony\Component\HttpFoundation\File\UploadedFile;
15:
16: 17: 18: 19: 20: 21: 22: 23:
24: class FileBag extends ParameterBag
25: {
26: private static $fileKeys = array('error', 'name', 'size', 'tmp_name', 'type');
27:
28: 29: 30: 31: 32: 33: 34:
35: public function __construct(array $parameters = array())
36: {
37: $this->replace($parameters);
38: }
39:
40: 41: 42: 43: 44:
45: public function replace(array $files = array())
46: {
47: $this->parameters = array();
48: $this->add($files);
49: }
50:
51: 52: 53: 54: 55:
56: public function set($key, $value)
57: {
58: if (!is_array($value) && !$value instanceof UploadedFile) {
59: throw new \InvalidArgumentException('An uploaded file must be an array or an instance of UploadedFile.');
60: }
61:
62: parent::set($key, $this->convertFileInformation($value));
63: }
64:
65: 66: 67: 68: 69:
70: public function add(array $files = array())
71: {
72: foreach ($files as $key => $file) {
73: $this->set($key, $file);
74: }
75: }
76:
77: 78: 79: 80: 81: 82: 83:
84: protected function convertFileInformation($file)
85: {
86: if ($file instanceof UploadedFile) {
87: return $file;
88: }
89:
90: $file = $this->fixPhpFilesArray($file);
91: if (is_array($file)) {
92: $keys = array_keys($file);
93: sort($keys);
94:
95: if ($keys == self::$fileKeys) {
96: if (UPLOAD_ERR_NO_FILE == $file['error']) {
97: $file = null;
98: } else {
99: $file = new UploadedFile($file['tmp_name'], $file['name'], $file['type'], $file['size'], $file['error']);
100: }
101: } else {
102: $file = array_map(array($this, 'convertFileInformation'), $file);
103: }
104: }
105:
106: return $file;
107: }
108:
109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124:
125: protected function fixPhpFilesArray($data)
126: {
127: if (!is_array($data)) {
128: return $data;
129: }
130:
131: $keys = array_keys($data);
132: sort($keys);
133:
134: if (self::$fileKeys != $keys || !isset($data['name']) || !is_array($data['name'])) {
135: return $data;
136: }
137:
138: $files = $data;
139: foreach (self::$fileKeys as $k) {
140: unset($files[$k]);
141: }
142:
143: foreach (array_keys($data['name']) as $key) {
144: $files[$key] = $this->fixPhpFilesArray(array(
145: 'error' => $data['error'][$key],
146: 'name' => $data['name'][$key],
147: 'type' => $data['type'][$key],
148: 'tmp_name' => $data['tmp_name'][$key],
149: 'size' => $data['size'][$key]
150: ));
151: }
152:
153: return $files;
154: }
155: }
156: