summaryrefslogtreecommitdiffstats
path: root/examples/lib/FilterReplace.php
blob: 962555c90132d1a26243892f7b5a61516db73566 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php

namespace lib;

use php_user_filter;

class FilterReplace extends php_user_filter
{
    const FILTER_NAME = 'convert.replace.';

    private $search;

    private $replace;

    public function onCreate()
    {
        if( strpos( $this->filtername, self::FILTER_NAME ) !== 0 ){
            return false;
        }

        $params = substr( $this->filtername, strlen( self::FILTER_NAME ) );

        if( !preg_match( '/([^:]+):([^$]+)$/', $params, $matches ) ){
            return false;
        }

        $this->search  = $matches[1];
        $this->replace = $matches[2];

        return true;
    }

    public function filter( $in, $out, &$consumed, $closing )
    {
        while( $res = stream_bucket_make_writeable( $in ) ){

            $res->data = str_replace( $this->search, $this->replace, $res->data );

            $consumed += $res->datalen;

            /** @noinspection PhpParamsInspection */
            stream_bucket_append( $out, $res );
        }

        return PSFS_PASS_ON;
    }
}