Will attempt to re-open stream in the event that it was closed unexpectedly.  Will use default if unable to
re-open custom

@see DefaultLogger::defaultStream()
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();
        }
    }
659000
public function initFromStream($stream)
    {
        if (!$stream instanceof StreamInterface) {
            $stream = new Stream($stream);
        }

        try {
            $offset = $stream->tell();
        } catch (\RuntimeException $e) {
            $offset = 0;
        }

        $shouldAndCanSeek = $offset !== 0 && $stream->isSeekable();

        if ($shouldAndCanSeek) {
            $stream->rewind();
        }

        try {
            $data = $stream->getContents();
        } catch (\RuntimeException $e) {
            $data = null;
        }

        if ($shouldAndCanSeek) {
            $stream->seek($offset);
        }

        if ($data) {
            return $this->initFromBinary($data);
        }

        throw new \Intervention\Image\Exception\NotReadableException(
            "Unable to init from given stream"
        );
    }
383949
public function rewind() : void
	{
		if (! \is_resource($this->resource))
		{
			throw new Exception\UnseekableStreamException('Stream is not resourceable');
		}

		if (! $this->isSeekable())
		{
			throw new Exception\UnseekableStreamException('Stream is not seekable');
		}

		$result = \fseek($this->resource, 0, \SEEK_SET);

		if (! (0 === $result))
		{
			throw new Exception\UnseekableStreamException('Unable to move the stream pointer to beginning');
		}
	}
497344
protected function openStream(string $uri)
    {
        $scheme = parse_url($uri, PHP_URL_SCHEME);

        if (!isset($scheme) || $scheme === '') {
            throw new \InvalidArgumentException("Invalid URI '$uri'; scheme missing");
        }

        $reporting = error_reporting(error_reporting() & ~(E_WARNING | E_NOTICE));
        try {
            $stream = fopen($uri, 'w'); // Just in case stream wrapper throws an exception
        } finally {
            error_reporting($reporting);
        }

        if (!is_resource($stream)) {
            ['message' => $message] = error_get_last() ?? ['message' => "Failed to open '$uri'"];
            throw new \RuntimeException($message);
        }

        return $stream;
    }
213392
protected function createStream()
    {
        $stream = Psr7\stream_for();
        $this->writePartHeadersTo($stream);
        $stream->rewind();
        return $stream;
    }
189634
public function stream_close()
	{
		if ( !\is_resource($this->resource) )
		{
			return;
		}

		// Close the resource.
		if ( $this->resourceType === static::RESOURCE_TYPE_FILE )
		{
			\fclose( $this->resource );
		}
		else if ( $this->ssl )
		{
			\fclose( $this->resource );
			// Only save the file when not loaded locally.
			$saveFile = $this->getSaveFile();
			\file_put_contents( $saveFile, $this->content );
		}
		else if ( $this->resourceType === static::RESOURCE_TYPE_SOCKET )
		{
			// This could throw errors if the socket is not connected on some systems.
			@\socket_shutdown( $this->resource );
			\socket_close( $this->resource );
			// Only save the file when not loaded locally.
			$saveFile = $this->getSaveFile();
			\file_put_contents( $saveFile, $this->content );
		}

		// Leave the resource for garbage clean-up.
		$this->resource = NULL;

		// Reset so we do not overwrite a file unintentionally for the next request.
		static::clearSaveFile();
	}
582167
public function end()
    {
        if (!$this->_seekable) {
            throw new RuntimeException("Cannot seek on non seekable stream.");
        }
        if (!count($this->_streams)) {
            throw new RuntimeException('The stream container is empty no seek operation is possible.');
        }
        $this->_current = count($this->_streams) - 1;
        $stream = $this->_streams[$this->_current];
        $stream->seek(0, SEEK_END);
    }
1097683
public function close()
	{
		if (!$this->fh)
		{
			throw new \RuntimeException('File not open');
		}

		// Capture PHP errors
		$php_errormsg = 'Error Unknown';
		$track_errors = ini_get('track_errors');
		ini_set('track_errors', true);

		switch ($this->processingmethod)
		{
			case 'gz':
				$res = gzclose($this->fh);
				break;

			case 'bz':
				$res = bzclose($this->fh);
				break;

			case 'f':
			default:
				$res = fclose($this->fh);
				break;
		}

		if (!$res)
		{
			throw new \RuntimeException($php_errormsg);
		}
		else
		{
			// Reset this
			$this->fh = null;
		}

		// If we wrote, chmod the file after it's closed
		if ($this->openmode[0] == 'w')
		{
			$this->chmod();
		}

		// Restore error tracking to what it was before
		ini_set('track_errors', $track_errors);

		// Return the result
		return true;
	}
113724
public function withLocalScope()
    {
        if ($this->isClosed()) {
            throw new \RuntimeException("The stream is closed");
        }
        
        if (!$this->isGlobal()) {
            return $this;
        }
        
        $stream = clone $this;
        
        fwrite($stream->handle, (string)$this);
        
        return $stream;
    }
914498
private void openStream() throws IOException {
    if (mIn != null) { // stream is already open
      return;
    }
    GetObjectRequest getReq = new GetObjectRequest(mBucketName, mKey);
    // If the position is 0, setting range is redundant and causes an error if the file is 0 length
    if (mPos > 0) {
      getReq.setRange(mPos);
    }
    AmazonS3Exception lastException = null;
    while (mRetryPolicy.attempt()) {
      try {
        mIn = mClient.getObject(getReq).getObjectContent();
        return;
      } catch (AmazonS3Exception e) {
        LOG.warn("Attempt {} to open key {} in bucket {} failed with exception : {}",
            mRetryPolicy.getAttemptCount(), mKey, mBucketName, e.toString());
        if (e.getStatusCode() != HttpStatus.SC_NOT_FOUND) {
          throw new IOException(e);
        }
        // Key does not exist
        lastException = e;
      }
    }
    // Failed after retrying key does not exist
    throw new IOException(lastException);
  }
796294
public function init($streamWrapper = self::STREAM_WRAPPER_TEMP, $maxMemory = 5242880)
    {

        // weather we've already set a filename open the input stream
        if ($tmpFilename = $this->getTmpFilename()) {
            if (!$this->inputStream = fopen($tmpFilename, 'r+')) {
                throw new \Exception(sprintf('Can\'t open input temporary filename %s', $tmpFilename));
            }
        } else {
            if (!$this->inputStream = fopen($streamWrapper . '/maxmemory:' . $maxMemory, 'r+')) {
                throw new \Exception(sprintf('Can\'t open stream wrapper %s', $streamWrapper));
            }
        }
    }
709399
private function getStream()
    {
        if ($this->stream && get_resource_type($this->stream) === 'Unknown') {
            fclose($this->stream);
            $this->stream = null;
        }
        if (!$this->stream) {
            $this->stream = @fopen($this->streamUrl, 'a');
            if (!$this->stream) {
                LoggerPolicy::processIOError("Error open $this->streamUrl");
                $this->stream = null;
            }
        }

        return $this->stream;
    }
706332
public function close()
    {
        if ($this->resource) {
            // Error suppression, as resource might already be closed
            $meta = @\stream_get_meta_data($this->resource);

            if ($meta && \strpos($meta["mode"], "+") !== false) {
                @\stream_socket_shutdown($this->resource, \STREAM_SHUT_RD);
            } else {
                @\fclose($this->resource);
            }
            $this->resource = null;
        }

        $this->free();
    }
216485
public function stream()
	{
		$fp = fopen("php://memory", 'r+');
		fwrite($fp, $this->output());
		rewind($fp);
		return $fp;
	}
1053239
public function stream_close()
    {
        @fclose($this->temporaryFileHandle);
        
        // Upload the file?
        if ($this->writeMode) {
            // Make sure the container exists
            if (! $this->containerExists($this->fileName)) {
                $this->getStorageClient($this->fileName)->createContainer($this->getContainerName($this->fileName));
            }
            
            $mimeTypeGuesser = MimeTypeGuesser::getInstance();
            $createBlobOptions = new CreateBlobOptions();
            $createBlobOptions->setBlobContentType($mimeTypeGuesser->guess($this->temporaryFileName));
            
            // Upload the file
            try {
                $result = $this->getStorageClient($this->fileName)->createBlockBlob($this->getContainerName($this->fileName), $this->getFileName($this->fileName), fopen($this->temporaryFileName, "r"), $createBlobOptions);
            } catch (Exception $ex) {
                $this->cleanup();
                
                throw $ex;
            }
        }
        
        $this->cleanup();
    }
1353682
public static function resetStd()
    {
        if (!static::$daemonize || static::$_OS !== OS_TYPE_LINUX) {
            return;
        }
        global $STDOUT, $STDERR;
        $handle = fopen(static::$stdoutFile, "a");
        if ($handle) {
            unset($handle);
            set_error_handler(function(){});
            fclose($STDOUT);
            fclose($STDERR);
            fclose(STDOUT);
            fclose(STDERR);
            $STDOUT = fopen(static::$stdoutFile, "a");
            $STDERR = fopen(static::$stdoutFile, "a");
            // change output stream
            static::$_outputStream = null;
            static::outputStream($STDOUT);
            restore_error_handler();
        } else {
            throw new Exception('can not open stdoutFile ' . static::$stdoutFile);
        }
    }
904591
public function stream_open($uri, $mode, $options, &$opened_path)
    {
        $this->uri = $uri;
        $path = $this->getTarget();

        $this->isReadOnly = StreamUtil::modeIsReadOnly($mode);
        $this->isWriteOnly = StreamUtil::modeIsWriteOnly($mode);
        $this->isAppendMode = StreamUtil::modeIsAppendable($mode);

        $this->handle = $this->invoke($this, 'getStream', [$path, $mode], 'fopen');

        if ($this->handle && $options & STREAM_USE_PATH) {
            $opened_path = $path;
        }

        return is_resource($this->handle);
    }