|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Recoded\WordPressBlockParser; |
| 4 | + |
| 5 | +use Recoded\WordPressBlockParser\Blocks\AbstractBlock; |
| 6 | +use Stringable; |
| 7 | + |
| 8 | +final class BlockReplacer implements Stringable |
| 9 | +{ |
| 10 | + private string $replacedContent; |
| 11 | + private int $offsetDifference = 0; |
| 12 | + |
| 13 | + /** |
| 14 | + * Create a new BlockReplacer instance. |
| 15 | + * |
| 16 | + * @param string $content |
| 17 | + * @return void |
| 18 | + */ |
| 19 | + public function __construct( |
| 20 | + public readonly string $content, |
| 21 | + ) { |
| 22 | + $this->replacedContent = $content; |
| 23 | + } |
| 24 | + |
| 25 | + /** |
| 26 | + * Create a new replacer from content string. |
| 27 | + * |
| 28 | + * @param string $content |
| 29 | + * @return self |
| 30 | + */ |
| 31 | + public static function create(string $content): self |
| 32 | + { |
| 33 | + return new self($content); |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * Replace the given block in the content. |
| 38 | + * |
| 39 | + * @param \Recoded\WordPressBlockParser\Blocks\AbstractBlock $block |
| 40 | + * @param string $replacement |
| 41 | + * @return $this |
| 42 | + */ |
| 43 | + public function replace(AbstractBlock $block, string $replacement): self |
| 44 | + { |
| 45 | + $from = $block->getStart() + $this->offsetDifference; |
| 46 | + $to = $block->getEnd() + $this->offsetDifference; |
| 47 | + |
| 48 | + $this->replacedContent = substr($this->replacedContent, 0, $from) |
| 49 | + . $replacement |
| 50 | + . substr($this->replacedContent, $to); |
| 51 | + |
| 52 | + $this->offsetDifference += strlen($replacement) - ($to - $from); |
| 53 | + |
| 54 | + return $this; |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * Get the replaced content. |
| 59 | + * |
| 60 | + * @return string |
| 61 | + */ |
| 62 | + public function __toString(): string |
| 63 | + { |
| 64 | + return $this->replacedContent; |
| 65 | + } |
| 66 | +} |
0 commit comments