Skip to content

Commit

Permalink
FileMock: fixed read-only/write-only modes
Browse files Browse the repository at this point in the history
- cannot read from write-only mock
- cannot write into read-only mock
  • Loading branch information
milo committed Mar 19, 2016
1 parent 27e063f commit d11db94
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 8 deletions.
19 changes: 18 additions & 1 deletion src/Framework/FileMock.php
Expand Up @@ -24,6 +24,12 @@ class FileMock
/** @var int */
private $pos;

/** @var bool */
private $isReadable;

/** @var bool */
private $isWritable;


/**
* @return string file name
Expand All @@ -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'");
Expand All @@ -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;
Expand All @@ -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
Expand Down
14 changes: 7 additions & 7 deletions tests/Framework/FileMock.phpt
Expand Up @@ -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'),
);

Expand All @@ -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'),
);

Expand Down

0 comments on commit d11db94

Please sign in to comment.