Cron Translator

repository·main·Indexed 43 days ago

https://github.com/lorisleiva/cron-translator

A PHP library that converts standard CRON expressions and special @ extended expressions into human-readable, natural language strings. It supports multiple locales, 24-hour time formats, and provides classes like CronExpression and CronType for parsing and analyzing cron schedules.

Tokens
2.7K
Snippets
15
Records
15
Agent score
54%

What's inside Cron Translator

  1. Translate CRON expressions with locale and 24-hour format

    main

    The translate() method accepts two optional arguments to customize the output:

    1. Locale (string): The language code for the translation (e.g., 'fr' for French).
    2. Use 24-hour format (boolean): Whether to use the 24-hour clock instead of the default 12-hour format.

    Supported locales include: ar, cs, da, de, en, es, fr, hi, lv, nl, pl, pt, ro, ru, sk, tr, ua, vi, zh, and zh-TW.

    // Translate to French with 12-hour format
    CronTranslator::translate('30 18 * * *', 'fr');       // => Chaque jour à 6:30pm
    
    // Translate to French with 24-hour format
    CronTranslator::translate('30 18 * * *', 'fr', true); // => Chaque jour à 18:30
  2. Translate CRON expressions with translate()

    main

    Use the CronTranslator::translate() method to convert a CRON expression into a human-readable string. By default, it uses English and a 12-hour time format.

    use Lorisleiva
    
    CronTranslator::translate('* * * * *');       // => Every minute
    CronTranslator::translate('30 22 * * *');     // => Every day at 10:30pm
    CronTranslator::translate('0 0 1 1 *');       // => Every year on January the 1st at 12:00am
  3. Handle cron parsing errors with CronParsingException

    main

    When using the library to translate or parse a cron expression, a CronParsingException is thrown if the provided expression is invalid or cannot be parsed. You can catch this exception to identify which specific cron string caused the failure. The exception message includes the invalid cron expression that triggered the error.

    try {
        $translator->translate($invalidCron);
    } catch (\Lorisleiva\CronTranslator\CronParsingException $e) {
        echo $e->getMessage(); // "Failed to parse the following CRON expression: [invalid_cron]"
    }
  4. Create CronType instances manually

    main

    If you are building a cron schedule programmatically rather than parsing a string, you can use the following static factory methods on the CronType class:

    • every(): Represents a * pattern.
    • increment(int $increment, int $count = 1): Represents an increment pattern (e.g., */2).
    • multiple(int $count): Represents a pattern with a specific number of values (e.g., 1,2,3).
    • once(int $value): Represents a single fixed value (e.g., 5).
    use Lorisleiva\CronTranslator\CronType;
    
    $every = CronType::every();
    $increment = CronType::increment(5, 10);
    $multiple = CronType::multiple(3);
    $once = CronType::once(1);
  5. Retrieve localized translations with lang()

    main

    The lang(string $key, array $replacements = []) method retrieves a localized translation string from the $translations array using dot notation for the $key. It supports placeholder replacement using the :key syntax and automatically handles pluralization based on the translation content.

    // Example usage assuming $translations is configured
    $translation = $cron->lang('fields.minute', ['value' => '5']);
  6. Instantiate CronExpression to parse cron strings

    main

    The CronExpression class is the primary entry point for parsing and translating cron expressions. You can create a new instance by passing the cron string to the constructor. You can also optionally provide a custom $translations array and specify whether to use a 24-hour time format via $timeFormat24hours.

    use Lorisleiva\CronTranslator\CronExpression;
    
    // Basic instantiation
    $cron = new CronExpression('*/5 * * * *');
    
    // Instantiation with custom translations and 24-hour format
    $translations = [...];
    $cron = new CronExpression('*/5 * * * *', $translations, true);
  7. Translate a cron expression with CronTranslator::translate()

    main

    Use the CronTranslator::translate() static method to convert a cron expression into a human-readable string. The method supports standard cron syntax as well as special @ extended cron expressions (like @daily or @hourly).

    Parameters

    • string $cron: The cron expression to translate.
    • string $locale: The locale for the translation (defaults to 'en').
    • bool $timeFormat24hours: Whether to use 24-hour time format (defaults to false).

    Exceptions

    • Throws CronParsingException if the provided cron expression is invalid or cannot be parsed.
    use Lorisleiva\CronTranslator\CronTranslator;
    
    // Basic translation
    $translation = CronTranslator::translate('0 0 * * *');
    
    // Translation with specific locale and 24-hour format
    $translation = CronTranslator::translate('0 0 * * *', 'en', true);
    
    // Translating extended cron expressions
    $translation = CronTranslator::translate('@daily');
  8. Get parsed cron fields

    main

    Use the getFields() method to retrieve an array containing the individual field objects representing the parsed cron expression. The returned array contains objects of types MinutesField, HoursField, DaysOfMonthField, MonthsField, and DaysOfWeekField in that order.

    $fields = $cron->getFields();
    // Returns [MinutesField, HoursField, DaysOfMonthField, MonthsField, DaysOfWeekField]
  9. Parse cron expressions using CronType::parse()

    main

    Use CronType::parse(string $expression) to convert a cron expression string into a CronType instance. This method automatically detects the schedule pattern (e.g., every, once, multiple, or increment) based on the syntax of the expression.

    Supported patterns include:

    • * (Every)
    • 1 (Once)
    • 1,2,5 (Multiple)
    • 1-5 (Multiple or Once)
    • */2 or 1-4/10 (Increment)

    Throws a CronParsingException if the expression is invalid.

    use Lorisleiva\CronTranslator\CronType;
    
    $cronType = CronType::parse('*/5');
  10. Retrieve localized countable translations with langCountable()

    main

    The langCountable(string $type, int $number, string $case = 'nominative') method is used to get translations that depend on a specific count and grammatical case. It looks up the $type in the $translations array and selects the appropriate value based on the $number and $case. It replaces the :number placeholder in the resulting string with the provided integer.

    // Example usage
    $translation = $cron->langCountable('some_type', 5, 'nominative');
  11. Check the type of a CronType instance

    main

    Once you have a CronType instance, you can verify its schedule type using the hasType() method. This method accepts one or more type strings as arguments and returns true if the instance's type matches any of the provided arguments.

    Supported type constants are available in CronType::TYPES:

    • 'Every'
    • 'Increment'
    • 'Multiple'
    • 'Once'
    use Lorisleiva\CronTranslator\CronType;
    
    $cronType = CronType::parse('*/5');
    
    if ($cronType->hasType('Increment')) {
        // Handle increment logic
    }
    
    // You can also check for multiple types
    if ($cronType->hasType('Every', 'Increment')) {
        // ...
    }