Skip to content

Instantly share code, notes, and snippets.

@yammerjp
Created January 21, 2025 04:18
Show Gist options
  • Select an option

  • Save yammerjp/b130eecad389a88e4130b5915075f0b0 to your computer and use it in GitHub Desktop.

Select an option

Save yammerjp/b130eecad389a88e4130b5915075f0b0 to your computer and use it in GitHub Desktop.
PHPのstream wrapperを自分で定義する
<?php
class YammerCustomStreamWrapper {
private $position;
private $data;
public $context;
public function stream_open($path, $mode, $options, &$opened_path) {
switch ($path) {
case "yammer://me":
$this->data = "yammer";
break;
case "yammer://company":
$this->data = "GMO Pepabo, Inc.";
break;
case "yammer://like":
$this->data = "awk";
break;
case "yammer://hobby":
$this->data = "SCUBA Diving";
break;
default:
$this->data = "";
break;
}
// 独自の初期データを設定
// $this->data = "This is some example data for my custom stream.";
$this->position = 0;
return true;
}
public function stream_stat() {
return [];
}
public function stream_read($count) {
// 指定されたバイト数を読み込む
$ret = substr($this->data, $this->position, $count);
$this->position += strlen($ret);
return $ret;
}
public function stream_eof() {
// 終端に達したかどうかを返す
return $this->position >= strlen($this->data);
}
public function stream_write($data) {
// データを書き込む(この例ではサポートしていません)
return 0;
}
public function stream_tell() {
// 現在の位置を返す
return $this->position;
}
public function stream_seek($offset, $whence) {
// ストリーム内での位置を設定
switch ($whence) {
case SEEK_SET:
if ($offset < strlen($this->data) && $offset >= 0) {
$this->position = $offset;
return true;
}
return false;
case SEEK_CUR:
if ($offset >= 0) {
$this->position += $offset;
return true;
}
return false;
case SEEK_END:
if (strlen($this->data) + $offset >= 0) {
$this->position = strlen($this->data) + $offset;
return true;
}
return false;
default:
return false;
}
}
public function stream_close() {
// リソースが終了する際に呼び出される
}
}
// 新しいプロトコルの登録
stream_wrapper_register("yammer", "YammerCustomStreamWrapper")
or die("Failed to register protocol");
// カスタムプロトコルを使用してデータを読み込む
echo 'file_get_contents("yammer://me") :'. file_get_contents("yammer://me") . "\n";
echo 'file_get_contents("yammer://company) :'. file_get_contents("yammer://company") . "\n";
echo 'file_get_contents("yammer://like") :'. file_get_contents("yammer://like") . "\n";
echo 'file_get_contents("yammer://hobby") :'. file_get_contents("yammer://hobby") . "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment