Skip to content

Commit

Permalink
Add a preClose callback
Browse files Browse the repository at this point in the history
This is useful in case a callback wants to do something with the stream
right before it gets closed.

Signed-off-by: Roeland Jago Douma <roeland@famdouma.nl>
  • Loading branch information
rullzer committed Feb 14, 2019
1 parent 74d0347 commit 3c98a75
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/CallbackWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ class CallbackWrapper extends Wrapper {
*/
protected $readDirCallBack;

/**
* @var callable
*/
protected $preCloseCallback;

/**
* Wraps a stream with the provided callbacks
*
Expand All @@ -56,14 +61,15 @@ class CallbackWrapper extends Wrapper {
*
* @throws \BadMethodCallException
*/
public static function wrap($source, $read = null, $write = null, $close = null, $readDir = null) {
public static function wrap($source, $read = null, $write = null, $close = null, $readDir = null, $preClose = null) {
$context = stream_context_create(array(
'callback' => array(
'source' => $source,
'read' => $read,
'write' => $write,
'close' => $close,
'readDir' => $readDir
'readDir' => $readDir,
'preClose' => $preClose,
)
));
return Wrapper::wrapSource($source, $context, 'callback', '\Icewind\Streams\CallbackWrapper');
Expand All @@ -76,6 +82,7 @@ protected function open() {
$this->writeCallback = $context['write'];
$this->closeCallback = $context['close'];
$this->readDirCallBack = $context['readDir'];
$this->preCloseCallback = $context['preClose'];
return true;
}

Expand Down Expand Up @@ -104,6 +111,11 @@ public function stream_write($data) {
}

public function stream_close() {
if (is_callable($this->preCloseCallback)) {
call_user_func($this->preCloseCallback, $this->loadContext('callback')['source']);
// prevent further calls by potential PHP 7 GC ghosts
$this->preCloseCallback = null;
}
$result = parent::stream_close();
if (is_callable($this->closeCallback)) {
call_user_func($this->closeCallback);
Expand Down

0 comments on commit 3c98a75

Please sign in to comment.