Skip to content

Commit

Permalink
Merge pull request #382 from php-vcr/268-abstract-code-transform-spli…
Browse files Browse the repository at this point in the history
…ts-in-middle-of-file

FIX: Read the whole stream and perform code transformations
  • Loading branch information
higidi committed Dec 27, 2022
2 parents a8eda85 + 9871fec commit bddc1fe
Showing 1 changed file with 18 additions and 7 deletions.
25 changes: 18 additions & 7 deletions src/VCR/CodeTransform/AbstractCodeTransform.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,19 @@ abstract class AbstractCodeTransform extends \php_user_filter
{
public const NAME = 'vcr_abstract_filter';

private string $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));
Assertion::true(
$isRegistered,
sprintf('Failed registering stream filter "%s" on stream "%s"', static::class, static::NAME)
);
}
}

Expand All @@ -30,20 +35,26 @@ public function register(): void
* @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): int
public function filter($in, $out, &$consumed, bool $closing): int
{
while ($bucket = stream_bucket_make_writeable($in)) {
$bucket->data = $this->transformCode($bucket->data);
$consumed += $bucket->datalen;
stream_bucket_append($out, $bucket);
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;
}

Expand Down

0 comments on commit bddc1fe

Please sign in to comment.