Stillat / blade-parser

A library that makes it simple to parse, analyze, and manipulate Blade templates. Designed with tool makers in mind ❤️
https://stillat.com/blade-parser
MIT License
125 stars 2 forks source link

Adds Node Transformation Helper Utilities #19

Closed JohnathonKoster closed 1 year ago

JohnathonKoster commented 1 year ago

This PR introduces a new abstract node transformer. This transformer provides a simple way to iterate all nodes in a document and change the output, while skipping over nodes within the document.

For example, if we had the following node transformer implementation:

<?php

use Stillat\BladeParser\Compiler\Transformers\NodeTransformer;
use Stillat\BladeParser\Nodes\DirectiveNode;

class CustomTransformer extends NodeTransformer
{
    public function transformNode($node): ?string
    {
        if (! $node instanceof DirectiveNode || $node->content != 'custom') {
            return null;
        }

        $this->skipToNode($node->isClosedBy);

        return '@include("something-here")';
    }
}

we could transform a document like so:

<?php

use Stillat\BladeParser\Document\Document;
use Stillat\BladeParser\Document\DocumentOptions;

$doc = Document::fromText($template, documentOptions: new DocumentOptions(
            withCoreDirectives: false,
            customDirectives: ['custom', 'endcustom']
        ))->resolveStructures();

$result = (new CustomTransformer())->transformDocument($doc);

to produce the final result:

The beginning.

@include("something-here")

The end.