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

Mtt Bundle Laravel Package

canaltp/mtt-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require canaltp/mtt-bundle
    

    Follow the installation guide to enable the bundle in config/bundles.php and run migrations.

  2. First Use Case: Generate a basic timetable PDF for a bus stop:

    use CanalTP\MttBundle\Generator\TimetableGenerator;
    
    $generator = new TimetableGenerator();
    $timetable = $generator->generateFromStop(
        $stopId,
        $date,
        $templateName = 'default'
    );
    $timetable->saveAs('path/to/output.pdf');
    
  3. Key Files:

    • config/packages/canaltp_mtt.yaml (Configuration)
    • src/Entity/ (Custom entities like Stop, Line, Calendar)
    • templates/ (Twig templates for timetables)

Implementation Patterns

Core Workflows

  1. Timetable Generation:

    • Use TimetableGenerator for dynamic PDFs:
      $generator = $this->get('canaltp_mtt.generator');
      $timetable = $generator->generateFromStop($stopId, $date);
      return new BinaryFileResponse($timetable->getContent(), 200, [
          'Content-Type' => 'application/pdf',
          'Content-Disposition' => 'attachment; filename="timetable.pdf"',
      ]);
      
    • Templates: Override default templates in templates/canaltp_mtt/ (e.g., default.html.twig).
  2. Calendar Management:

    • Create/edit calendars via CRUD endpoints (enabled by default routes):
      // Example: Create a calendar
      $calendar = new Calendar();
      $calendar->setName('Weekend Holidays');
      $calendar->setRules([/* JSON rules */]);
      $em->persist($calendar);
      $em->flush();
      
    • Export calendars to CSV:
      $exporter = $this->get('canaltp_mtt.calendar.exporter');
      $csv = $exporter->exportToCsv([$calendar1, $calendar2]);
      
  3. Annotations & Highlights:

    • Add annotations to timetables via Annotation entity:
      $annotation = new Annotation();
      $annotation->setStop($stop);
      $annotation->setMessage('Construction work');
      $annotation->setStartDate($startDate);
      $annotation->setEndDate($endDate);
      $em->persist($annotation);
      
  4. Multi-Page & Paper Sizes:

    • Configure paper sizes in config/packages/canaltp_mtt.yaml:
      canaltp_mtt:
          default_paper_size: 'A4'
          allowed_sizes: ['A3', 'A4', 'A5']
      

Integration Tips

  • Symfony Events: Listen to canaltp_mtt.timetable.pre_generate to modify timetable data before PDF generation.
  • API Endpoints: Use FOSRestBundle to expose timetable generation as an API:
    # config/routes.yaml
    canaltp_mtt_timetable:
        path: /api/timetables/{stopId}/{date}
        methods: GET
        defaults:
            _controller: 'canaltp_mtt.controller:TimetableController::generateAction'
    
  • Queue Jobs: Offload PDF generation to a queue (e.g., Symfony Messenger) for large timetables:
    $message = new GenerateTimetableMessage($stopId, $date);
    $this->messageBus->dispatch($message);
    

Gotchas and Tips

Pitfalls

  1. Template Overrides:

    • Ensure custom templates extend the base template (canaltp_mtt/base.html.twig).
    • Gotcha: Twig 2.x compatibility requires updating constraints (see #153).
  2. Cascading Deletes:

    • Entities like Annotation and Calendar use ON DELETE CASCADE. Test deletions carefully to avoid unintended data loss.
  3. OPCache Issues:

    • Clear OPCache after uploading new templates (fixed in #160):
      php bin/console cache:clear --env=prod
      
  4. CSV Exports:

    • Calendars with networks may fail to export (fixed in #138). Ensure network field is populated.
  5. Reserved Keywords:

    • Avoid using True as a class name (fixed in #150).

Debugging Tips

  • Log Timetable Generation: Enable debug mode in config/packages/dev/canaltp_mtt.yaml:

    canaltp_mtt:
        debug: true
    

    Logs will appear in var/log/dev.log.

  • Validate Calendars: Use the CalendarValidator service to check rules before generation:

    $validator = $this->get('canaltp_mtt.validator.calendar');
    $errors = $validator->validate($calendar);
    
  • Test Coverage: Run tests with fixed dates to avoid flaky tests (fixed in #156):

    DATE_FIXED=2023-01-01 php bin/phpunit
    

Extension Points

  1. Custom Generators: Extend AbstractGenerator to support new output formats (e.g., SVG):

    class SvgTimetableGenerator extends AbstractGenerator {
        public function generate(): string {
            // Custom SVG logic
        }
    }
    

    Register the service in services.yaml:

    services:
        CanalTP\MttBundle\Generator\SvgTimetableGenerator:
            tags: ['canaltp_mtt.generator']
    
  2. Annotation Providers: Implement AnnotationProviderInterface to fetch annotations from external sources (e.g., a database):

    class ExternalAnnotationProvider implements AnnotationProviderInterface {
        public function getAnnotations(Stop $stop, \DateTime $date): array {
            // Fetch from external API
        }
    }
    
  3. Twig Extensions: Add custom filters/functions to Twig for timetable templates:

    // src/Twig/AppExtension.php
    class AppExtension extends \Twig\Extension\AbstractExtension {
        public function getFunctions() {
            return [
                new \Twig\TwigFunction('format_time', [$this, 'formatTime']),
            ];
        }
    }
    

    Register the extension in services.yaml:

    services:
        App\Twig\AppExtension:
            tags: ['twig.extension']
    
  4. Event Listeners: Subscribe to events to modify timetable data dynamically:

    // src/EventListener/TimetableListener.php
    class TimetableListener implements EventSubscriberInterface {
        public static function getSubscribedEvents() {
            return [
                'canaltp_mtt.timetable.pre_generate' => 'onPreGenerate',
            ];
        }
    
        public function onPreGenerate(PreGenerateEvent $event) {
            $event->getTimetable()->addAnnotation(new Annotation());
        }
    }
    
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.
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
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