Skip to content

Commit

Permalink
FIX: Read the whole stream and perform code transformations
Browse files Browse the repository at this point in the history
First read the whole stream and afterwards perform code transformations.
This will ensure to also replace code, which is divided into chunks while
reading a file.

Fixes #268
  • Loading branch information
higidi committed Dec 27, 2022
1 parent a8eda85 commit 1917d66
Showing 1 changed file with 21 additions and 9 deletions.
30 changes: 21 additions & 9 deletions src/VCR/CodeTransform/AbstractCodeTransform.php
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)) {
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 @@ -29,21 +34,28 @@ public function register(): void
*
* @param resource $in
* @param resource $out
* @param int $consumed
* @param bool $closing
* @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 1917d66

Please sign in to comment.