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

Subconverter Bundle Laravel Package

crossknowledge/subconverter-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require crossknowledge/subconverter-bundle
    

    Register the bundle in config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 3.x):

    CrossKnowledge\SubConverterBundle\CrossKnowledgeSubConverterBundle::class => ['all' => true],
    
  2. First Use Case: Convert an SRT file to WebVTT in a controller:

    use Symfony\Component\HttpFoundation\File\UploadedFile;
    
    public function convertSubtitles(UploadedFile $file, string $format)
    {
        $converter = $this->get('crossknowledge.subconverterbundle.converter');
        $outputPath = sys_get_temp_dir() . '/converted.' . $format;
        $converter->convert($file->getPathname(), $outputPath, $format, false);
        return new FileResponse($outputPath);
    }
    
  3. Key Service: The crossknowledge.subconverterbundle.converter service is the entry point. Check its configuration in services.yaml (Symfony 4+) or services.xml (Symfony 3.x) for dependencies.


Implementation Patterns

Core Workflow

  1. File Handling:

    • Accept UploadedFile or raw paths. Validate input format before conversion:
      $supportedFormats = ['srt', 'webvtt', 'ttaf1', 'txt'];
      if (!in_array($inputFormat, $supportedFormats)) {
          throw new \InvalidArgumentException('Unsupported input format');
      }
      
  2. Batch Processing: Loop through uploaded files (e.g., from a form with multiple files):

    foreach ($request->files->get('subtitles') as $file) {
        $outputPath = $this->generateOutputPath($file, 'webvtt');
        $this->get('crossknowledge.subconverterbundle.converter')->convert(
            $file->getPathname(),
            $outputPath,
            'webvtt',
            true
        );
    }
    
  3. Integration with Storage: Use Symfony’s Filesystem or Storage components to handle output paths dynamically:

    $storage = $this->get('oneup_flysystem.storage_filesystem');
    $file = $storage->write('subtitles/converted.webvtt', $convertedContent);
    
  4. Command-Line Conversion: Create a console command for background processing:

    namespace App\Command;
    use Symfony\Component\Console\Command\Command;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Output\OutputInterface;
    
    class ConvertSubtitlesCommand extends Command
    {
        protected function execute(InputInterface $input, OutputInterface $output)
        {
            $converter = $this->get('crossknowledge.subconverterbundle.converter');
            $converter->convert(
                $input->getArgument('input'),
                $input->getArgument('output'),
                $input->getArgument('format'),
                $input->getOption('bom')
            );
            $output->writeln('Conversion complete!');
        }
    }
    
  5. Event-Driven Workflows: Trigger conversions after file uploads via Symfony events:

    // config/services.yaml
    App\EventListener\SubtitleUploadListener:
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
    

Gotchas and Tips

Pitfalls

  1. Format Limitations:

    • TTAF1 (Timed Text Authoring Format 1) is read-only in this bundle. Attempting to convert to TTAF1 will fail silently or throw an error. Validate output format:
      $allowedOutputFormats = ['srt', 'webvtt', 'txt'];
      if (!in_array($outputFormat, $allowedOutputFormats)) {
          throw new \RuntimeException('TTAF1 output not supported');
      }
      
  2. BOM Handling:

    • includeBom only affects output for txt and webvtt. Ignoring it for SRT/TTAF1 may cause encoding issues in downstream tools.
  3. File Locking:

    • Concurrent conversions on the same file can corrupt output. Use locks or unique temp paths:
      $tempPath = tempnam(sys_get_temp_dir(), 'sub_') . '.' . $outputFormat;
      
  4. Encoding Issues:

    • Assume UTF-8 input/output. For legacy files, pre-process with mb_convert_encoding:
      $content = mb_convert_encoding(file_get_contents($inputPath), 'UTF-8', 'ISO-8859-1');
      
  5. Deprecated Methods:

    • The bundle is last updated in 2019. Test thoroughly with modern Symfony versions (5.4+). Override services if needed:
      # config/services.yaml
      CrossKnowledge\SubConverterBundle\Service\Converter:
          arguments:
              $someDependency: '@new_service'
      

Debugging Tips

  1. Log Conversion Steps: Decorate the converter service to log inputs/outputs:

    // src/Service/ConverterLogger.php
    class ConverterLogger implements ConverterInterface
    {
        private $decorated;
        private $logger;
    
        public function __construct(ConverterInterface $converter, LoggerInterface $logger)
        {
            $this->decorated = $converter;
            $this->logger = $logger;
        }
    
        public function convert($input, $output, $format, $bom)
        {
            $this->logger->info('Converting', [
                'input' => $input,
                'output' => $output,
                'format' => $format,
            ]);
            return $this->decorated->convert($input, $output, $format, $bom);
        }
    }
    
  2. Validate Output: Use a post-conversion validator (e.g., check WebVTT structure with regex):

    private function validateWebVTT(string $content): bool
    {
        return preg_match('/^WEBVTT\n(?:[^\S\r\n]+\r?\n)?/m', $content) === 1;
    }
    
  3. Fallback for Unsupported Formats: Use a fallback converter (e.g., spatie/subtitle) for unsupported formats:

    if (!in_array($format, ['srt', 'webvtt', 'txt'])) {
        $fallbackConverter = new \Spatie\Subtitle\Converter();
        return $fallbackConverter->convert($inputPath, $outputPath, $format);
    }
    

Extension Points

  1. Custom Format Support: Extend the bundle by creating a new converter class and overriding the service:

    // src/Service/CustomConverter.php
    class CustomConverter implements ConverterInterface
    {
        public function convert($input, $output, $format, $bom)
        {
            if ($format === 'custom') {
                // Implement custom logic
                return $this->writeCustomFormat($input, $output);
            }
            // Delegate to original converter
            return $this->get('crossknowledge.subconverterbundle.converter')->convert($input, $output, $format, $bom);
        }
    }
    
  2. Pre/Post-Processing Hooks: Use Symfony’s compiler passes or event listeners to inject logic:

    // src/EventListener/SubtitleEventListener.php
    class SubtitleEventListener
    {
        public function onSubtitleConvert(SubtitleConvertEvent $event)
        {
            $event->setInput($this->preProcess($event->getInput()));
        }
    }
    
  3. Configuration Overrides: Override default settings (e.g., temp directory) via config/packages/cross_knowledge_sub_converter.yaml:

    cross_knowledge_sub_converter:
        temp_dir: '%kernel.project_dir%/var/subtitles_temp'
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle