3 * This file is part of vfsStream.
5 * For the full copyright and license information, please view the LICENSE
6 * file that was distributed with this source code.
8 * @package org\bovigo\vfs
10 namespace org\bovigo\vfs\content;
12 * File content implementation to mock large files.
14 * When content is written via write() the data will be written into the
15 * positions according to the current offset.
16 * When content is read via read() it will use the already written data. If no
17 * data is written at the offsets to read those offsets will be filled with
19 * Please note that accessing the whole content via content() will deliver a
20 * string with the length of the originally defined size. It is not advisable to
21 * do so with large sizes, except you have enough memory and time. :-)
25 class LargeFileContent extends SeekableFileContent implements FileContent
28 * byte array of written content
32 private $content = array();
43 * @param int $size file size in bytes
45 public function __construct($size)
51 * create large file with given size in kilobyte
53 * @param int $kilobyte
54 * @return LargeFileContent
56 public static function withKilobytes($kilobyte)
58 return new self($kilobyte * 1024);
62 * create large file with given size in megabyte
64 * @param int $megabyte
65 * @return LargeFileContent
67 public static function withMegabytes($megabyte)
69 return self::withKilobytes($megabyte * 1024);
73 * create large file with given size in gigabyte
75 * @param int $gigabyte
76 * @return LargeFileContent
78 public static function withGigabytes($gigabyte)
80 return self::withMegabytes($gigabyte * 1024);
84 * returns actual content
88 public function content()
90 return $this->doRead(0, $this->size);
94 * returns size of content
98 public function size()
104 * actual reading of given byte count starting at given offset
109 protected function doRead($offset, $count)
111 if (($offset + $count) > $this->size) {
112 $count = $this->size - $offset;
116 for ($i = 0; $i < $count; $i++) {
117 if (isset($this->content[$i + $offset])) {
118 $result .= $this->content[$i + $offset];
128 * actual writing of data with specified length at given offset
130 * @param string $data
134 protected function doWrite($data, $offset, $length)
136 for ($i = 0; $i < $length; $i++) {
137 $this->content[$i + $offset] = $data{$i};
140 if ($offset >= $this->size) {
141 $this->size += $length;
142 } elseif (($offset + $length) > $this->size) {
143 $this->size = $offset + $length;
148 * Truncates a file to a given length
150 * @param int $size length to truncate file to
153 public function truncate($size)
156 foreach (array_filter(array_keys($this->content),
157 function($pos) use ($size)
159 return $pos >= $size;
162 unset($this->content[$removePos]);