From d11db949378ab0ee7865f70c43de5e87101cd03f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miloslav=20H=C5=AFla?= Date: Fri, 4 Mar 2016 09:08:32 +0100 Subject: [PATCH] FileMock: fixed read-only/write-only modes - cannot read from write-only mock - cannot write into read-only mock --- src/Framework/FileMock.php | 19 ++++++++++++++++++- tests/Framework/FileMock.phpt | 14 +++++++------- 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/src/Framework/FileMock.php b/src/Framework/FileMock.php index d4997632..e4dae173 100644 --- a/src/Framework/FileMock.php +++ b/src/Framework/FileMock.php @@ -24,6 +24,12 @@ class FileMock /** @var int */ private $pos; + /** @var bool */ + private $isReadable; + + /** @var bool */ + private $isWritable; + /** * @return string file name @@ -49,7 +55,7 @@ public static function register() public function stream_open($path, $mode) { - if (!preg_match('#^([rwaxc])#', $mode, $m)) { + if (!preg_match('#^([rwaxc]).*?(\+)?#', $mode, $m)) { // Windows: failed to open stream: Bad file descriptor // Linux: failed to open stream: Illegal seek $this->warning("failed to open stream: Invalid mode '$mode'"); @@ -70,12 +76,19 @@ public function stream_open($path, $mode) $this->content = & self::$files[$path]; $this->pos = $m[1] === 'a' ? strlen($this->content) : 0; + $this->isReadable = isset($m[2]) || $m[1] === 'r'; + $this->isWritable = isset($m[2]) || $m[1] !== 'r'; + return TRUE; } public function stream_read($len) { + if (!$this->isReadable) { + return ''; + } + $res = substr($this->content, $this->pos, $len); $this->pos += strlen($res); return $res; @@ -84,6 +97,10 @@ public function stream_read($len) public function stream_write($data) { + if (!$this->isWritable) { + return 0; + } + $this->content = substr($this->content, 0, $this->pos) . str_repeat("\x00", max(0, $this->pos - strlen($this->content))) . $data diff --git a/tests/Framework/FileMock.phpt b/tests/Framework/FileMock.phpt index 1d5b9560..7d96efea 100644 --- a/tests/Framework/FileMock.phpt +++ b/tests/Framework/FileMock.phpt @@ -101,11 +101,11 @@ test(function () { 'r+' => array('ABC', 'ABC'), 'w' => array('', ''), 'w+' => array('', ''), - 'a' => array('ABC', 'ABC'), + 'a' => array('ABC', ''), 'a+' => array('ABC', 'ABC'), 'x' => array('', ''), 'x+' => array('', ''), - 'c' => array('ABC', 'ABC'), + 'c' => array('ABC', ''), 'c+' => array('ABC', 'ABC'), ); @@ -126,15 +126,15 @@ test(function () { FileMock::$files = array(); $cases = array( - 'r' => array('_BC', '_BC'), + 'r' => array('ABC', 'ABC'), 'r+' => array('_BC', '_BC'), - 'w' => array('_', '_'), + 'w' => array('_', ''), 'w+' => array('_', '_'), - 'a' => array('ABC_', 'ABC_'), + 'a' => array('ABC_', ''), 'a+' => array('ABC_', 'ABC_'), - 'x' => array('_', '_'), + 'x' => array('_', ''), 'x+' => array('_', '_'), - 'c' => array('_BC', '_BC'), + 'c' => array('_BC', ''), 'c+' => array('_BC', '_BC'), );