Skip to content

Instantly share code, notes, and snippets.

@Padam87
Created August 22, 2021 20:49
Show Gist options
  • Save Padam87/3825951526bd10a735dedfa26a3bf4ed to your computer and use it in GitHub Desktop.
Save Padam87/3825951526bd10a735dedfa26a3bf4ed to your computer and use it in GitHub Desktop.
<?php
namespace App\Flysystem;
use GuzzleHttp\Psr7\Utils;
use League\Flysystem\FilesystemReader;
use Psr\Http\Message\StreamInterface;
class StreamWrapper
{
private static FilesystemReader $filesystem;
/** @var resource */
public $context;
/** @var StreamInterface */
private ?StreamInterface $stream = null;
/** @var string r, r+, or w */
private ?string $mode = null;
public static function register(FilesystemReader $filesystem, $scheme = 'flysystem')
{
self::$filesystem = $filesystem;
if (in_array($scheme, stream_get_wrappers())) {
stream_wrapper_unregister($scheme);
}
stream_wrapper_register($scheme, __CLASS__);
}
protected function createStream($path): StreamInterface
{
$path = str_replace('flysystem://', '', $path);
$content = self::$filesystem->read($path);
return Utils::streamFor($content, ['size' => mb_strlen($content, '8bit')]);
}
protected function getStream($path): StreamInterface
{
if ($this->stream === null) {
$this->stream = $this->createStream($path);
}
return $this->stream;
}
public function stream_open($path, $mode, $options, &$opened_path)
{
$this->mode = $mode;
$this->getStream($path);
return true;
}
public function stream_read($count)
{
return $this->stream->read($count);
}
public function stream_write($data)
{
return (int) $this->stream->write($data);
}
public function stream_tell()
{
return $this->stream->tell();
}
public function stream_eof()
{
return $this->stream->eof();
}
public function stream_seek($offset, $whence)
{
try {
$this->stream->seek($offset, $whence);
} catch (\Exception $e) {
return false;
}
return true;
}
public function stream_cast($castAs)
{
$stream = clone($this->stream);
return $stream->detach();
}
public function stream_stat()
{
static $modeMap = [
'r' => 33060,
'rb' => 33060,
'r+' => 33206,
'w' => 33188,
'wb' => 33188
];
return [
'dev' => 0,
'ino' => 0,
'mode' => $modeMap[$this->mode],
'nlink' => 0,
'uid' => 0,
'gid' => 0,
'rdev' => -1,
'size' => $this->stream->getSize() ?: 0,
'atime' => 0,
'mtime' => 0,
'ctime' => 0,
'blksize' => -1,
'blocks' => -1,
];
}
public function url_stat($path, $flags)
{
$this->getStream($path);
return [
'dev' => 0,
'ino' => 0,
'mode' => 0100777,
'nlink' => 0,
'uid' => 0,
'gid' => 0,
'rdev' => -1,
'size' => $this->stream->getSize() ?: 0,
'atime' => 0,
'mtime' => 0,
'ctime' => 0,
'blksize' => -1,
'blocks' => -1,
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment