Assert that a stream is attached.

@return void
@throws \BadMethodCallException
519690
protected function assertAttached(): void
    {
        if (!isset($this->stream)) {
            throw new \BadMethodCallException("Stream is not attached");
        }

        if (!is_resource($this->stream)) {
            throw new \RuntimeException("Stream has closed unexpectedly");
        }
    }
259441
private function detectLineBreak(): void
    {
        $sample = $this->stream->read(10000);

        // Rewind stream if seekable, else decorate the stream so it doesn't have to be rewound.
        if ($this->stream->isSeekable()) {
            $this->stream->rewind();
        } else {
            $this->stream = new AppendStream([
                StreamFactoryDiscovery::find()->createStream($sample),
                $this->stream,
            ]);
        }

        // Adapted from https://stackoverflow.com/questions/11066857
        // Surrounded eols with spaces so they can be split like words
        $sample = preg_replace('/[^\r\n]*(\r\n|\n|\r)/','\1 ', $sample);
        // split words
        $parts = explode(' ', $sample);
        // count number of eol character occurrences
        $arr = array_count_values($parts);
        // choose one with most occurrences
        arsort($arr);
        $eol = key($arr);
        // ensure eol char is valid
        $eol = in_array($eol, ["\n", "\r", "\r\n"], true) ? $eol : "\n";

        $this->eol = $eol;
    }
345097
private function isDataOnStream()
    {
        $read = [$this->connection];
        $write = null;
        $except = null;
        $hasStreamInfo = @stream_select($read, $write, $except, 0);

        if ($hasStreamInfo === false) {
            // can return `false` if used in combination with `pcntl_signal` and lead to false errors here
            $error = error_get_last();
            if ($error && isset($error['message']) && stripos($error['message'], 'interrupted system call') === false) {
                throw new ConnectionException(
                    'Check failed to determine if the socket is readable.',
                    $this->activeHost
                );
            }
            return null;
        }

        return !empty($read);
    }
953101
function isEOF()
    {
        if ($this->_t__wrap_stream->isEOF())
            ## wrap stream is on the end
            return true;

        if ($this->getSegmentLimit() == -1)
            return false;

        return ($this->_t__wrap_stream->getCurrOffset() >= $this->getSegmentOffset() + $this->getSegmentLimit());
    }
629882
public function isStreamWrapped()
	{
		$maybeStreamWrapped = $this->partCount > 1 && $this->firstPart !== '' && $this->parts[1] === '' && ':' === substr($this->firstPart, -1);
		if (! $maybeStreamWrapped) {
			return false;
		}
		$name = substr($this->firstPart, 0, -1);
		return in_array($name, stream_get_wrappers());
	}
899716
public function tell() : int
	{
		if (! \is_resource($this->resource))
		{
			throw new Exception\UntellableStreamException('Stream is not resourceable');
		}

		$result = \ftell($this->resource);

		if (false === $result)
		{
			throw new Exception\UntellableStreamException('Unable to get the stream pointer position');
		}

		return $result;
	}
1134023
public function stream()
    {
        $key = $this->data['key'];
        unset($this->data['key']);
        $path = $this->getPath() . '/' . $key;
        if (!array_key_exists('end', $this->data)) {
            $patch = $this->jsonPatch->generate($path, JsonPatch::ACTION_ADD, $this->data, false);
        } else {
            $patch = $this->jsonPatch->generate($path . '/end', JsonPatch::ACTION_ADD, $this->data['end'], false);
        }

        $this->dataSource->save($this->process, [$patch]);
        $this->data = [];
    }
8959
protected function attemptStreamRecovery()
    {
        if ('resource' === gettype($this->stream))
        {
            @fflush($this->stream);
            @fclose($this->stream);
        }

        $this->stream = fopen($this->streamURI, $this->streamMode);
        if (false === $this->stream)
        {
            trigger_error(sprintf(
                '%s - Unable to write to "%s" and re-open attempt failed, will default to php-output',
                get_called_class(),
                $this->streamURI));

            $this->stream = $this->defaultStream();
        }
    }
913503
protected function attach($newStream)
    {
        if (is_resource($newStream) === false) {
            throw new InvalidArgumentException(__METHOD__ . ' argument must be a valid PHP resource');
        }

        if ($this->isAttached() === true) {
            $this->detach();
        }

        $this->stream = $newStream;
    }
922459
public function disconnect() {
		$this->log->log("Disconnecting...",  XMPPHP_Log::LEVEL_VERBOSE);
		if(false == (bool) $this->socket) {
			return;
		}
		$this->reconnect = false;
		$this->send($this->stream_end);
		$this->sent_disconnect = true;
		$this->processUntil('end_stream', 5);
		$this->disconnected = true;
	}
202767
function isSeekable()
    {
        $this->assertMetaData();
        
        if ($this->getMetaKey('wrapper_type')) {
            // This is a wrapper resource; challenge seekable ...
            if (false === $pos = ftell($this->rHandler))
                throw new \RuntimeException('Unable to determine stream position');

            try {
                // TODO Stream Reach EOF When Seek On it Sometimes!!
                if (-1 === @fseek($this->rHandler, $pos, SEEK_SET))
                    return false;
            } catch (\Exception $e) {
                // Maybe Fallback into wrapper handler for seek
                return false;
            }
        }
        
        return (bool) $this->getMetaKey('seekable');
    }
1322929
public function stream_flush()
    {
        if (!$this->getResource()) {
            return false;
        }

        $buffer = $this->getDataBuffer();
        $bufferWritten = $buffer;
        $retVal = true;
        if (!empty($buffer)) {

            $object = $this->getResource()->getObject();
            $mimetype = $this->getService()->guessFileType($this->getResource()->getResourceName());
            $object->content_type = $mimetype;
            $object->setData($buffer);
            $object->Create();
        }

       if (strlen($bufferWritten) ==  strlen($buffer)) {
            $this->setDataBuffer(null);
        } else {
            $this->setDataBuffer($buffer);
        }
        $this->setDataBuffer(null);

        return $retVal;
    }
1138031
public function unlock() : void
    {
        if ($this->closed) {
            throw new IoException('The stream is closed.');
        }

        try {
            $result = ErrorCatcher::run(function() {
                return flock($this->handle, LOCK_UN);
            });
        } catch (\ErrorException $e) {
            throw new IoException($e->getMessage(), 0, $e);
        }

        if ($result === false) {
            throw new IoException('Failed to release the lock.');
        }
    }
395720
function tell()
    {
        if (!$this->_assertUsable())
            throw new \RuntimeException('No resource available; cannot tell position');

        if (false === $r = ftell($this->rHandler))
            throw new \RuntimeException('Unable to determine stream position');

        return $r;
    }
1294143
private function registerStreams()
    {
        foreach ($this->_streamWrappers as $wrappers) {
            foreach ($wrappers as $wrapper) {
                if (false === in_array($wrapper['protocol'], $this->_availableWrappers)) {
                    stream_wrapper_register($wrapper['protocol'], $wrapper['classname']);
                    $this->_availableWrappers = stream_get_wrappers();
                }
            }
        }
    }
732794
function attachListener_() {
    if (isListening) { return; }
    isListening = true;

    unsubFunc = Events.eventListener(target, eventName, function() {
      if (outputStream.closed) {
        detachListener_();
      } else {
        Util.apply(boundEmit, arguments);
      }
    });

    onClose(outputStream, detachListener_);
  }
289373
public function stream_close()
    {
        if ($this->_upload !== null) {
            $this->_upload->complete();
            $this->_upload = null;
        }
        if ($this->_download !== null) {
            $this->_download = null;
        }
    }