Skip to content

Commit

Permalink
Add guards for closed file before fopen, fwrite, fread, fclose. Closes
Browse files Browse the repository at this point in the history
  • Loading branch information
mike42 committed Jun 26, 2018
1 parent 9d4da6a commit bfc8265
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/Mike42/Escpos/PrintConnectors/FilePrintConnector.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,15 +50,20 @@ public function __destruct()
*/
public function finalize()
{
fclose($this -> fp);
$this -> fp = false;
if ($this -> fp !== false) {
fclose($this -> fp);
$this -> fp = false;
}
}

/* (non-PHPdoc)
* @see PrintConnector::read()
*/
public function read($len)
{
if ($this -> fp === false) {
throw new Exception("PrintConnector has been closed, cannot read input.");
}
return fread($this -> fp, $len);
}

Expand All @@ -69,6 +74,9 @@ public function read($len)
*/
public function write($data)
{
if ($this -> fp === false) {
throw new Exception("PrintConnector has been closed, cannot send output.");
}
fwrite($this -> fp, $data);
}
}
29 changes: 29 additions & 0 deletions test/unit/FilePrintConnectorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php
use Mike42\Escpos\PrintConnectors\FilePrintConnector;

class FilePrintConnectorTest extends PHPUnit_Framework_TestCase
{
public function testTmpfile()
{
// Should attempt to send data to the local printer by writing to it
$tmpfname = tempnam("/tmp", "php");
$connector = new FilePrintConnector($tmpfname);
$connector -> finalize();
$connector -> finalize(); // Silently do nothing if printer already closed
unlink($tmpfname);
}

public function testReadAfterClose()
{
// Should attempt to send data to the local printer by writing to it
$this -> setExpectedException('Exception');
$tmpfname = tempnam("/tmp", "php");
try {
$connector = new FilePrintConnector($tmpfname);
$connector -> finalize();
$connector -> write("Test");
} finally {
unlink($tmpfname);
}
}
}

0 comments on commit bfc8265

Please sign in to comment.