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

Time Distance Bundle Laravel Package

dtl/time-distance-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dtl/time-distance-bundle
    

    Add to config/bundles.php:

    Dtl\TimeDistanceBundle\DtlTimeDistanceBundle::class => ['all' => true],
    

    Publish config (optional):

    php artisan config:publish dtl/time-distance-bundle
    
  2. First Use Case: Display a formatted distance in a Twig template:

    {# Convert 5000 meters to miles #}
    {{ 5000|format_distance('miles') }}
    

    Output: 3.106856 (miles).


Implementation Patterns

Common Workflows

  1. Distance Conversion in Views: Use format_distance for dynamic unit switching (e.g., toggle between km/miles in a profile page):

    {% set distance = user.distance_ran|format_distance(user.preferred_unit) %}
    
  2. Stopwatch Formatting: Convert timestamps (e.g., from a race) to stopwatch format:

    {{ race.duration_seconds|seconds_to_stopwatch }}
    

    Use case: Leaderboards, race results, or user activity logs.

  3. Pace Calculations: Display athlete performance metrics:

    {{ athlete.total_time|average_pace(athlete.distance, 'km') }}
    

    Use case: Training dashboards, progress tracking.

  4. Form Integration: Bind distance inputs to normalized units (meters) in forms:

    // In a controller
    $form = $this->createForm(DistanceType::class, $user);
    
    {{ form_row(form.distance) }} {# Renders as <input type="number"> #}
    

    Tip: Validate normalized values in the controller (e.g., >= 0).

  5. Dynamic Unit Selection: Store user preferences in the database (e.g., preferred_distance_unit) and pass to Twig:

    {% set unit = user.preferred_distance_unit ?? 'km' %}
    {{ distance|format_distance(unit) }}
    

Integration Tips

  • API Responses: Return normalized values (meters/seconds) in JSON APIs, then format client-side or in Twig. Example:

    { "distance": 5000, "unit": "m" }
    
    {{ data.distance|format_distance(data.unit) }}
    
  • Localization: Extend the bundle’s DistanceConverter service to support custom units (e.g., nautical miles) by overriding the getConversionFactor method.

  • Testing: Mock the DistanceConverter and StopwatchFormatter services in PHPUnit:

    $this->app->instance(DistanceConverter::class, $mockConverter);
    

Gotchas and Tips

Pitfalls

  1. Unit Mismatch:

    • The bundle assumes all distances are stored in meters. Passing non-normalized values (e.g., km) to format_distance will yield incorrect results.
    • Fix: Convert inputs to meters before passing to Twig:
      {{ 5|format_distance('km') }} {# Incorrect: 5 km → 5000 m → 3.106856 miles #}
      {{ 5000|format_distance('miles') }} {# Correct #}
      
  2. Stopwatch Overflow:

    • seconds_to_stopwatch does not handle values > 24 hours gracefully (e.g., 604800 seconds = 1 week → 168:00:00).
    • Tip: Add validation in the controller or use JavaScript for large durations.
  3. Form Type Quirks:

    • The DistanceType and StopwatchType form fields do not enforce normalization. Validate manually:
      $distance = $form->get('distance')->getData();
      if ($distance < 0) {
          $form->addError(...);
      }
      
  4. Precision Handling:

    • format_distance defaults to 6 decimal places. Override via the second argument:
      {{ 1000|format_distance('miles', 2) }} {# Output: 0.62 #}
      

Debugging

  • Check Config: Verify normalized_distance_unit in config/dtl_time_distance.php matches your data model (default: m).

    // config/dtl_time_distance.php
    return [
        'normalized_distance_unit' => 'm', // or 'ft', 'mi', etc.
    ];
    
  • Twig Filter Availability: Ensure the bundle is registered in bundles.php and Twig is auto-reloaded:

    php artisan config:clear
    php artisan cache:clear
    

Extension Points

  1. Custom Units: Extend the DistanceConverter service by binding a decorator:

    // src/Service/DistanceConverterDecorator.php
    class DistanceConverterDecorator extends DistanceConverter {
        public function getConversionFactor($unit) {
            $factor = parent::getConversionFactor($unit);
            return $unit === 'nautical_miles' ? $factor * 1.15078 : $factor;
        }
    }
    

    Register in services.yaml:

    Dtl\TimeDistanceBundle\Service\DistanceConverter: '@App\Service\DistanceConverterDecorator'
    
  2. Stopwatch Formatting: Override the StopwatchFormatter to customize separators or add milliseconds:

    // src/Twig/StopwatchExtension.php
    class StopwatchExtension extends \Dtl\TimeDistanceBundle\Twig\StopwatchExtension {
        public function getStopwatchFormat(int $seconds): string {
            // Custom logic (e.g., add milliseconds)
            return sprintf('%02d:%02d:%02d.%03d',
                floor($seconds / 3600),
                ($seconds % 3600) / 60,
                $seconds % 60,
                ($seconds * 1000) % 1000
            );
        }
    }
    

    Bind the extension in services.yaml:

    twig.extension.stopwatch: '@App\Twig\StopwatchExtension'
    
  3. Form Type Extensions: Add attributes or constraints to DistanceType/StopwatchType by extending the class and overriding configureOptions or buildForm.

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.
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
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours