自定义 Stream:
http://php.net/manual/zh/stream.streamwrapper.example-1.php
应用场景:
<?php
/**
* Example of stream filtering.
*/
// Open two file handles.
$in = fopen('test.txt.bz2', 'rb');
$out = fopen('test-uppercase.txt', 'wb');
// Add a decode filter to the first.
stream_filter_prepend($in, 'bzip2.decompress', STREAM_FILTER_READ);
// Change the charset from ISO-8859-1 to UTF-8
stream_filter_append($out, 'convert.iconv.ISO-8859-1/UTF-8', STREAM_FILTER_WRITE);
// Uppercase the entire string.
stream_filter_append($out, 'string.toupper', STREAM_FILTER_WRITE);
// Run ROT-13 on the output.
stream_filter_append($out, 'string.rot13', STREAM_FILTER_WRITE);
// Now copy. All of the filters are applied here.
stream_copy_to_stream($in, $out);
// Clean up.
fclose($in);
fclose($out);
流上下文:
流过滤器:
<?php
class DirtyWordsFilter extends php_user_filter{
/**
* @param resource $in 流入的桶队列
* @param resource $out 流出的桶队列
* @param int $consumed 处理的字节数
* @param bool $closing 是否是流中最后一个桶队列
* @return int
* 接收、处理再转运桶中的流数据,在该方法中,
我们迭代桶队列对象,把脏字替换成审查后的值
*/
public function filter($in, $out, &$consumed, $closing)
{
$words = ['grime', 'dirt', 'grease'];
$wordData = [];
foreach ($words as $word) {
$replacement = array_fill(0, mb_strlen($word), '*');
$wordData[$word] = implode('', $replacement);
}
$bad = array_keys($wordData);
$good = array_values($wordData);
// 迭代桶队列中的每个桶
while ($bucket = stream_bucket_make_writeable($in)) {
// 审查桶对象中的脏字
$bucket->data = str_replace($bad, $good, $bucket->data);
// 增加已处理的数据量
$consumed += $bucket->datalen;
// 把桶放入流向下游的队列中
stream_bucket_append($out, $bucket);
}
return PSFS_PASS_ON;
}
}
然后,我们必须使用 stream_filter_register() 函数注册这个自定义的 DirtyWordsFilter 流过滤器:
stream_filter_register('dirty_words_filter', 'DirtyWordsFilter');
第一个参数用于标识这个自定义过滤器的过滤器名,第二个参数是这个自定义过滤器的类名。接下来就可以使用这个自定义的流过滤器了:
$handle = fopen('test.txt', 'rb');
stream_filter_append($handle, 'dirty_words_filter');
while (feof($handle) !== true) {
echo fgets($handle);
}
fclose($handle);
修改 test.txt 内容如下:
abcdeefghijklmn
Hello LaravelAcademy!
grime
I hate dirty things!
运行上面的自定义过滤器脚本,结果如下:
http://php.net/manual/zh/wrappers.php
http://mp.weixin.qq.com/s/xHeP4RJjQK0y1rWA2u9MVQ
http://www.nowamagic.net/librarys/veda/detail/2587