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

Cron Expression Bundle Laravel Package

setono/cron-expression-bundle

Symfony bundle integrating dragonmantank/cron-expression. Provides a CronExpression form field and a Doctrine DBAL type to store Cron\CronExpression in entities, making it easy to validate, edit, and persist cron schedules in your app.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require setono/cron-expression-bundle
    
    • No manual bundle registration needed if using Symfony Flex.
  2. First Use Case:

    • Add the CronExpressionType to a form to validate and render cron expressions:
      use Setono\CronExpressionBundle\Form\Type\CronExpressionType;
      
      $builder->add('schedule', CronExpressionType::class);
      
  3. Database Integration:

    • Use the CronExpressionType Doctrine DBAL type for storing cron expressions in your database:
      use Setono\CronExpressionBundle\Doctrine\DBAL\Types\CronExpressionType;
      
      #[ORM\Column(type: CronExpressionType::CRON_EXPRESSION_TYPE)]
      private CronExpression $schedule;
      

Where to Look First

  • Form Integration: Setono\CronExpressionBundle\Form\Type\CronExpressionType
  • Doctrine DBAL Type: Setono\CronExpressionBundle\Doctrine\DBAL\Types\CronExpressionType
  • Validation: Built-in Symfony validator for cron expressions.

Implementation Patterns

Form Integration Workflow

  1. Basic Usage:

    $builder->add('cron_field', CronExpressionType::class);
    
    • Renders a text input with validation for cron expressions (e.g., * * * * *).
  2. Customization:

    • Validation Message: Override default error messages via form options:
      $builder->add('cron_field', CronExpressionType::class, [
          'error_bubbling' => true,
          'validation_message' => 'Invalid cron expression: {{ value }}',
      ]);
      
    • Placeholder: Add hints for users:
      $builder->add('cron_field', CronExpressionType::class, [
          'attr' => ['placeholder' => 'e.g., * * * * *'],
      ]);
      
  3. Dynamic Forms:

    • Use CronExpressionType in dynamic forms (e.g., Symfony UX Live Component) for real-time validation.

Database and Entity Patterns

  1. Storing Cron Expressions:

    • Map cron expressions to Doctrine entities using the custom DBAL type:
      #[ORM\Column(type: CronExpressionType::CRON_EXPRESSION_TYPE)]
      private CronExpression $schedule;
      
    • Automatically converts between string (e.g., "0 0 * * *") and CronExpression objects.
  2. Querying:

    • Use the CronExpression object in repositories to evaluate schedules:
      $expression = new CronExpression($entity->getSchedule());
      if ($expression->isDue()) {
          // Execute logic
      }
      
  3. Migrations:

    • When adding the column, ensure the DBAL type is registered in your migration:
      $this->addColumn('tasks', 'schedule', 'cron_expression');
      

Validation and Business Logic

  1. Symfony Validator:

    • The bundle integrates with Symfony’s validator. Invalid cron expressions (e.g., "invalid") trigger validation errors automatically.
  2. Custom Validation:

    • Extend validation logic by creating a custom constraint:
      use Symfony\Component\Validator\Constraints as Assert;
      
      #[Assert\CronExpression]
      private string $schedule;
      
    • Override messages in your validator configuration:
      # config/validator/validation.yaml
      Setono\CronExpressionBundle\Validator\Constraints\CronExpression:
          message: 'The cron expression "{{ value }}" is invalid.'
      
  3. Time Zone Handling:

    • Cron expressions are evaluated in the system’s default time zone. For timezone-aware logic, wrap evaluations:
      $expression = new CronExpression($cronString, new \DateTimeZone('America/New_York'));
      

Testing Patterns

  1. Unit Testing Forms:

    • Test cron expression validation in form types:
      $form = $this->factory->create(TaskType::class);
      $form->submit('invalid');
      $this->assertFalse($form->isValid());
      
  2. Database Tests:

    • Verify DBAL type serialization/deserialization:
      $connection = $this->getConnection();
      $connection->insert('tasks', ['schedule' => '0 0 * * *']);
      $result = $connection->fetchAssociative('SELECT schedule FROM tasks');
      $this->assertInstanceOf(CronExpression::class, $result['schedule']);
      
  3. Scheduling Logic:

    • Test cron expression evaluation in time-sensitive logic:
      $expression = new CronExpression('0 0 * * *');
      $this->assertTrue($expression->isDue(new \DateTime('2023-01-01 00:00:00')));
      

Gotchas and Tips

Common Pitfalls

  1. Invalid Cron Expressions:

    • The validator rejects malformed expressions (e.g., "*"). Handle edge cases in your form:
      $builder->add('schedule', CronExpressionType::class, [
          'error_bubbling' => true,
      ]);
      
    • Tip: Use a fallback value (e.g., "* * * * *") for required fields.
  2. Doctrine DBAL Type Conflicts:

    • If using Doctrine < 2.5 or DBAL < 3.0, ensure you’re on setono/cron-expression-bundle@^1.7 for compatibility.
    • Fix: Update dependencies or manually register the type in AppKernel:
      $this->registerDoctrineType(CronExpressionType::CRON_EXPRESSION_TYPE);
      
  3. Time Zone Mismatches:

    • Cron expressions are evaluated in the server’s default timezone. For user-specific schedules, store timezone info separately:
      #[ORM\Column]
      private string $timezone = 'UTC';
      
    • Tip: Use DateTimeImmutable with explicit time zones in business logic.
  4. Symfony 4 Deprecation:

    • The bundle dropped Symfony 4 support in v1.7.0. If upgrading from Symfony 4, test thoroughly or pin to ^1.6.

Debugging Tips

  1. Validation Errors:

    • Check the validator’s error message for invalid cron expressions:
      $errors = $form->getErrors();
      foreach ($errors as $error) {
          dump($error->getMessage());
      }
      
    • Common Fix: Ensure the cron string matches the format * * * * * * (5 or 6 fields).
  2. Database Serialization:

    • If cron expressions fail to save/load, verify the DBAL type is registered:
      $connection->getDatabasePlatform()->getDoctrineTypeMapping()[CronExpressionType::CRON_EXPRESSION_TYPE];
      
    • Fix: Clear cache (php bin/console cache:clear) after adding the type.
  3. Performance:

    • Parsing cron expressions is lightweight, but avoid evaluating them in loops. Cache CronExpression objects:
      private static $cachedExpressions = [];
      $expression = self::$cachedExpressions[$cronString] ?? new CronExpression($cronString);
      

Extension Points

  1. Custom Form Types:

    • Extend CronExpressionType to add features like:
      • Auto-complete: Integrate with Symfony UX Autocomplete.
      • Presets: Add dropdown options for common schedules (e.g., "Daily at 9 AM").
      class ExtendedCronExpressionType extends CronExpressionType {
          public function configureOptions(OptionsResolver $resolver) {
              $resolver->setDefaults([
                  'presets' => ['daily' => '0 0 * * *'],
              ]);
          }
      }
      
  2. Custom Validators:

    • Add constraints to enforce business rules (e.g., "only allow weekdays"):
      use Setono\CronExpressionBundle\Validator\Constraints\CronExpression;
      
      #[Assert\CronExpression]
      #[Assert\Expression(
          "value.isDue(new \DateTime('now')) || value.isDue(new \DateTime('now +1 hour'))",
          message: "Schedule must run within the next hour."
      )]
      private string $schedule;
      
  3. Doctrine Events:

    • Listen for cron expression changes to trigger side effects:
      $entityManager->getEventManager()->addEventListener(
          ORM\Events::prePersist,
          function (ORM\PrePersistEventArgs $args) {
              $entity = $args->getObject();
              if ($entity instanceof Task) {
                  // Log or validate cron expression changes
              }
          }
      );
      

Configuration Quirks

  1. Bundle Auto-Configuration:
    • The bundle auto-registers in Symfony Flex projects. For manual setups, ensure bundles.php includes:
      Setono\CronExpressionBundle\SetonoC
      
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.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky