jbowens / jBBCode

A lightweight but extensible BBCode parser
http://jbbcode.com
MIT License
164 stars 32 forks source link

asText override by custom CodeDefinition #6

Closed WiS3 closed 11 years ago

WiS3 commented 11 years ago

Hello, it is possible to override the getAsText method by a custom CodeDefinition?

For example, i have my own Youtube CodeDefinition, and when i call Parser.getAsText(), instead to show the Youtube URL/ID, i want to have 'Youtube Video'.

I tried to add a new public asText() function in my Youtube CodeDefinition, returning 'Youtube Video', but doesn't work, so i think has to be implemented by modifing the core...

I've tried, and failed, so can you help me getting this done? Thank you.

EDIT: I got it working.

Here how i did, if someone need this functionality, or improve it

ElementNode.php : Replace function

public function getAsText() {
    if( $this->codeDefinition ){
        return $this->codeDefinition->asText( $this );
    }else{
        $s="";
    foreach($this->getChildren() as $child)
        $s .= $child->getAsText();
    return $s;
    }
}

CodeDefinition.php : Add function

/**
 * Accepts an ElementNode that is defined by this CodeDefinition and returns the content without markup of the element.
 * This can be overridden by a custom CodeDefinitions so that the content can be directly manipulated.
 * 
 * @param el the element to return a text only representation of
 * 
 * @return the parsed text without markup of this element (INCLUDING ITS CHILDREN)
 */  
public function asText( ElementNode $el )
{
        $s="";
    foreach($el->getChildren() as $child)
        $s .= $child->getAsText();
    return $s;
}

and inside your custom CodeDefinition class, add:

...    

public function asText( JBBCode\ElementNode $el )
{
    return 'Your Custom Text';
}

...

I'm testing it right now to see if there are issues.

jbowens commented 11 years ago

You're right. I don't think there's currently a way to achieve this through the API. I'll include this in the next release, which should be coming in the next couple days.