Completed
Push — master ( 853cd9...2961ef )
by Nazar
04:00
created

File_stream::stream_tell()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 2
c 1
b 0
f 1
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
1
<?php
2
/**
3
 * @package   CleverStyle Framework
4
 * @author    Nazar Mokrynskyi <[email protected]>
5
 * @copyright Copyright (c) 2016, Nazar Mokrynskyi
6
 * @license   MIT License, see license.txt
7
 */
8
namespace cs\Request;
9
use
10
	cs\Request;
11
12
/**
13
 * Stream wrapper created in order to be used as virtual stream which actually represents uploaded file, which is only available in form of stream, but we
14
 * sometimes need to handle it like regular file
15
 *
16
 * Usage:
17
 * * `fopen('request-file:///file', 'r')`
18
 * * `fopen('request-file:///file/0', 'r')`
19
 *
20
 * `/file` basically represents `cs\Request::files['file']` and `/file/0` `cs\Request::files['file'][0]`
21
 */
22
class File_stream {
23
	/**
24
	 * @var resource
25
	 */
26
	protected $stream;
27
	/**
28
	 * @var int
29
	 */
30
	protected $position;
31
32 6
	function stream_open ($path, $mode) {
33 6
		if ($mode != 'r' && $mode != 'rb') {
34 2
			return false;
35
		}
36 6
		$files = Request::instance()->files;
37 6
		foreach (explode('/', explode(':///', $path)[1]) as $file_path) {
38 6
			if (!isset($files[$file_path])) {
39 2
				return false;
40
			}
41 6
			$files = $files[$file_path];
42
		}
43 6
		$this->stream   = $files['stream'];
44 6
		$this->position = 0;
45 6
		return true;
46
	}
47
	/**
48
	 * @param int $length
49
	 *
50
	 * @return false|string
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use string.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
51
	 */
52 6
	function stream_read ($length) {
53 6
		fseek($this->stream, $this->position);
54 6
		$bytes          = fread($this->stream, $length);
55 6
		$this->position += strlen($bytes);
56 6
		return $bytes;
57
	}
58
	/**
59
	 * @return false|int
60
	 */
61
	function stream_tell () {
62
		return $this->position;
63
	}
64
	/**
65
	 * @return bool
66
	 */
67 6
	function stream_eof () {
68 6
		fseek($this->stream, $this->position);
69 6
		return feof($this->stream);
70
	}
71
	/**
72
	 * @param int $offset
73
	 * @param int $whence
74
	 *
75
	 * @return int
76
	 */
77 2
	function stream_seek ($offset, $whence = SEEK_SET) {
78 2
		fseek($this->stream, $this->position);
79 2
		$result         = fseek($this->stream, $offset, $whence);
80 2
		$this->position = ftell($this->stream);
81 2
		return $result;
82
	}
83
	/**
84
	 * @return array
85
	 */
86 6
	function stream_stat () {
87 6
		return fstat($this->stream);
88
	}
89
}
90