/
AbstractCodeTransform.php
66 lines (56 loc) · 1.67 KB
/
AbstractCodeTransform.php
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
namespace VCR\CodeTransform;
use function stream_get_filters;
use VCR\Util\Assertion;
/**
* A stream wrapper filter to transform code.
*/
abstract class AbstractCodeTransform extends \php_user_filter
{
public const NAME = 'vcr_abstract_filter';
/** @var string */
private $data = '';
/**
* Attaches the current filter to a stream.
*/
public function register(): void
{
if (!\in_array(static::NAME, stream_get_filters(), true)) {
$isRegistered = stream_filter_register(static::NAME, static::class);
Assertion::true(
$isRegistered,
sprintf('Failed registering stream filter "%s" on stream "%s"', static::class, static::NAME)
);
}
}
/**
* Applies the current filter to a provided stream.
*
* @param resource $in
* @param resource $out
* @param int $consumed
* @param bool $closing
*
* @return int PSFS_PASS_ON
*
* @see http://www.php.net/manual/en/php-user-filter.filter.php
*/
public function filter($in, $out, &$consumed, $closing)
{
while ($buffer = stream_bucket_make_writeable($in)) {
$this->data .= $buffer->data;
$consumed += $buffer->datalen;
}
if (!$closing) {
return \PSFS_FEED_ME;
}
$bucket = stream_bucket_new($this->stream, $this->transformCode($this->data));
$this->data = '';
stream_bucket_append($out, $bucket);
return \PSFS_PASS_ON;
}
/**
* Transcodes the provided data to whatever.
*/
abstract protected function transformCode(string $code): string;
}