Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Sonata Formatter Bundle Laravel Package

awaresoft/sonata-formatter-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation via Composer (if not symlinked):

    composer require awaresoft/sonata-formatter-bundle
    

    For local development, follow the README’s symlink instructions to modify the bundle directly.

  2. Enable the Bundle: Add to config/bundles.php:

    return [
        // ...
        Awaresoft\SonataFormatterBundle\SonataFormatterBundle::class => ['all' => true],
    ];
    
  3. Basic Configuration: Override default settings in config/packages/sonata_formatter.yaml:

    sonata_formatter:
        formats:
            rich_html: { mime_type: 'text/html', extensions: ['html', 'twig'] }
    
  4. First Use Case: Use the formatter in a Twig template:

    {{ content|sonata_formatter }}
    

    Or in a controller:

    $formatter = $this->get('sonata.formatter');
    $formattedContent = $formatter->format($content, 'rich_html');
    

Implementation Patterns

Core Workflows

  1. Content Formatting in Entities: Use the Sonata\MediaBundle or Sonata\FormatterBundle annotations to define formatter behavior:

    use Sonata\FormatterBundle\Annotation\Formatter;
    
    class Article {
        /**
         * @Formatter\Formatter("rich_html")
         */
        private $content;
    }
    
  2. Dynamic Format Selection: Pass formats dynamically in controllers:

    $format = $request->query->get('format', 'rich_html');
    $formatted = $formatter->format($content, $format);
    
  3. Integration with Doctrine: Use Sonata\FormatterBundle\Doctrine\Types\TextType for database storage:

    use Doctrine\DBAL\Types\TextType;
    use Sonata\FormatterBundle\Doctrine\Types\TextType as FormatterTextType;
    
    $builder->addColumn('content', FormatterTextType::NAME);
    
  4. Twig Extensions: Extend Twig with custom filters:

    // services.yaml
    Twig\TwigFilter:
        sonata_formatter_custom:
            tag: sonata_formatter
            arguments: ['@sonata.formatter']
    

    Usage:

    {{ content|sonata_formatter_custom('markdown') }}
    
  5. API Responses: Format content before JSON serialization:

    $data['content'] = $formatter->format($entity->getContent(), 'rich_html');
    return new JsonResponse($data);
    

Integration Tips

  • Symfony Forms: Use Sonata\FormatterBundle\Form\Type\FormatterType for form fields:

    $builder->add('content', FormatterType::class, [
        'format_field' => 'format',
        'source_field' => 'content',
        'source_field_options' => ['required' => false],
    ]);
    
  • Event Listeners: Trigger formatting on entity persistence:

    // services.yaml
    App\EventListener\FormatContentListener:
        tags:
            - { name: doctrine.event_listener, event: prePersist }
            - { name: doctrine.event_listener, event: preUpdate }
    
    class FormatContentListener {
        public function __construct(private FormatterInterface $formatter) {}
    
        public function prePersist(Entity $entity) {
            $entity->setContent($this->formatter->format($entity->getContent(), 'rich_html'));
        }
    }
    
  • Custom Formats: Define new formats in config:

    sonata_formatter:
        formats:
            custom_markdown:
                mime_type: 'text/markdown'
                extensions: ['md']
                service: sonata.formatter.text.markdown
    

Gotchas and Tips

Pitfalls

  1. Symlink Conflicts:

    • If using local symlinks, ensure autoload_psr4.php is updated manually after changes.
    • Clear cache after modifying the bundle:
      php bin/console cache:clear
      
  2. Backward Compatibility:

    • Avoid breaking changes (e.g., renaming methods or removing formats). Follow semver rules in the README.
  3. Doctrine Type Mismatch:

    • Ensure TextType is used for formatter fields in Doctrine migrations:
      $this->addSql('ALTER TABLE article CHANGE content content TEXT');
      
  4. Twig Auto-escaping:

    • Formatted content may escape HTML by default. Disable in Twig:
      {{ content|raw|sonata_formatter }}
      
  5. Performance:

    • Avoid formatting in loops or real-time (e.g., API responses). Cache formatted content when possible.

Debugging

  • Check Available Formats:

    php bin/console debug:container sonata.formatter
    

    Look for sonata.formatter.format.<name> services.

  • Log Formatter Errors: Enable debug mode and check logs for Sonata\FormatterBundle exceptions.

  • Validate Config: Use Symfony’s config validator:

    php bin/console config:validate sonata_formatter
    

Extension Points

  1. Custom Formatters: Create a service for new formats:

    # config/services.yaml
    App\Formatter\CustomFormatter:
        tags:
            - { name: sonata.formatter, format: 'custom_format' }
    
    class CustomFormatter implements FormatterInterface {
        public function format($content, $format) { /* ... */ }
    }
    
  2. Override Default Services: Replace existing formatters (e.g., sonata.formatter.text.html):

    services:
        sonata.formatter.text.html:
            class: App\Formatter\CustomHtmlFormatter
            arguments: ['@twig']
    
  3. Event Subscribers: Listen to sonata.formatter.format events for pre/post-processing:

    use Sonata\FormatterBundle\Event\FormatEvent;
    
    class CustomFormatterSubscriber implements EventSubscriberInterface {
        public static function getSubscribedEvents() {
            return [FormatEvent::NAME => 'onFormat'];
        }
    
        public function onFormat(FormatEvent $event) {
            $event->setContent(strtoupper($event->getContent()));
        }
    }
    
  4. Configuration Overrides: Merge custom formats without losing defaults:

    sonata_formatter:
        formats:
            rich_html:
                mime_type: 'text/html'
                extensions: ['html', 'twig']
            # Override existing or add new
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware