1 <?php
2
3 /*
4 * This file is part of the ICanBoogie package.
5 *
6 * (c) Olivier Laviale <olivier.laviale@gmail.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace ICanBoogie\HTTP;
13
14 /**
15 * Representation of a list of request files.
16 */
17 class FileList implements \ArrayAccess, \IteratorAggregate, \Countable
18 {
19 /**
20 * Creates a {@link FileList} instance.
21 *
22 * @param array|FileList|null $files
23 *
24 * @return FileList
25 */
26 static public function from($files)
27 {
28 if ($files instanceof self)
29 {
30 return clone $files;
31 }
32
33 if (!$files)
34 {
35 return new static([]);
36 }
37
38 foreach ($files as &$file)
39 {
40 $file = File::from($file);
41 }
42
43 return new static($files);
44 }
45
46 /**
47 * @var File[]
48 */
49 protected $list;
50
51 public function __construct(array $files = [])
52 {
53 foreach ($files as $id => $file)
54 {
55 $this[$id] = $file;
56 }
57 }
58
59 /**
60 * Checks if a file exists.
61 *
62 * @param string $id
63 *
64 * @return bool
65 */
66 public function offsetExists($id)
67 {
68 return isset($this->list[$id]);
69 }
70
71 /**
72 * Returns a file.
73 *
74 * @param string $id
75 *
76 * @return File|null A {@link File} instance, or `null` if it does not exists.
77 */
78 public function offsetGet($id)
79 {
80 if (!$this->offsetExists($id))
81 {
82 return null;
83 }
84
85 return $this->list[$id];
86 }
87
88 /**
89 * Adds a file.
90 *
91 * @param string $id
92 * @param string|array|File $file
93 */
94 public function offsetSet($id, $file)
95 {
96 if (!($file instanceof File || $file instanceof FileList))
97 {
98 $file = File::from($file);
99 }
100
101 $this->list[$id] = $file;
102 }
103
104 /**
105 * Removes a file.
106 *
107 * @param string $id
108 */
109 public function offsetUnset($id)
110 {
111 unset($this->list[$id]);
112 }
113
114 /**
115 * @inheritdoc
116 *
117 * @return \ArrayIterator
118 */
119 public function getIterator()
120 {
121 return new \ArrayIterator($this->list);
122 }
123
124 /**
125 * Returns the number of files in the collection.
126 *
127 * @return int
128 */
129 public function count()
130 {
131 return count($this->list);
132 }
133 }
134