phpsilverstripe-4

Silverstripe 4.11 / use custom class / ImageShortcodeProvider


In Silverstripe 4.11 CMS I try to add a custom class by default to all images set in tinymce - editor (HTMLEditorField). I thought i could do this within SilverStripe\Assets\Shortcodes\ImageShortcodeProvider within public static function handle_shortcode to change the output of ImageShortcodeProvider.

To use my own class i did a yml:

SilverStripe\Core\Injector\Injector:
  SilverStripe\Assets\Shortcodes\ImageShortcodeProvider:
    class: CustomImageShortcodeProvider

I copied all the code from the original class but made my changes in public static function handle_shortcode.

.........
 // Build the HTML tag
        $attrs = array_merge(
            // Set overrideable defaults ('alt' must be present regardless of contents)
            //['src' => '', 'alt' => ''],
            ['src' => '', 'alt' => '', 'class' => ''],
            
            // Use all other shortcode arguments
            $args,
            // But enforce some values
            //['id' => '', 'src' => $src]
            ['id' => '', 'src' => $src, 'class' => 'jquery-image-fluid']
        );
............

unfortunately this has no effect. if i edit the original class it works as aspected.

Can you please tell me what i am missing?


Solution

  • Shortcode parsers in Silverstripe framework are ultimately just callback - the class is just a convenient framing for it. The one you're trying to replace is registered as a callback here, which looks like this:

    use SilverStripe\View\Parsers\ShortcodeParser;
    use SilverStripe\Assets\Shortcodes\ImageShortcodeProvider;
    
    ShortcodeParser::get('default')->register('image', [ImageShortcodeProvider::class, 'handle_shortcode']);
    

    In other words, you cannot replace shortcode providers using dependency injection. You can however register your own provider over the top of the original one by using the above code snippet, replacing the callback with your own inside your _config.php file. In your case this would probably be:

    use SilverStripe\View\Parsers\ShortcodeParser;
    
    ShortcodeParser::get('default')->register('image', [CustomImageShortcodeProvider::class, 'handle_shortcode']);