Skip to content

Commit

Permalink
Validate frequency before save
Browse files Browse the repository at this point in the history
  • Loading branch information
fredden committed May 9, 2023
1 parent 26e6c5e commit 50a4bf7
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
2 changes: 2 additions & 0 deletions Controller/Adminhtml/Config/Job/Save.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ public function execute()
$group = $params['group'] ?: null;
$frequency = $params['frequency'] ?: null;
try {
$this->helper->validateFrequency($frequency);

$path = $this->helper->constructFrequencyPath($jobCode, $group);
$this->helper->saveJobFrequencyConfig($path, $frequency);
$this->cache->remove(self::SYSTEM_DEFAULT_IDENTIFIER);
Expand Down
28 changes: 27 additions & 1 deletion Helper/JobConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@

use EthanYehuda\CronjobManager\Model\Manager;
use EthanYehuda\CronjobManager\Model\ManagerFactory;
use Magento\Cron\Model\ScheduleFactory;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\App\Config\Storage\WriterInterface;
use Magento\Framework\Exception\CronException;
use Magento\Framework\Exception\ValidatorException;

class JobConfig extends AbstractHelper
Expand All @@ -21,11 +23,13 @@ class JobConfig extends AbstractHelper
* @param Context $context
* @param WriterInterface $configWriter
* @param ManagerFactory $managerFactory
* @param ScheduleFactory $scheduleFactory
*/
public function __construct(
Context $context,
private readonly WriterInterface $configWriter,
ManagerFactory $managerFactory
ManagerFactory $managerFactory,
private readonly ScheduleFactory $scheduleFactory,
) {
parent::__construct($context);
$this->manager = $managerFactory->create();
Expand Down Expand Up @@ -122,4 +126,26 @@ public function sanitizeJobConfig(array $job)
$job['method'] = !empty($job['method']) ? $job['method'] : '';
return $job;
}

/**
* Validate cronjob frequency string
*
* @param string|null $frequency
*
* @throws CronException
* @see \Magento\Cron\Model\Schedule::trySchedule()
*/
public function validateFrequency(?string $frequency): void
{
if ($frequency === null) {
return;
}

$schedule = $this->scheduleFactory->create();
$schedule->setCronExpr($frequency);

foreach ($schedule->getCronExprArr() as $expression) {
$schedule->matchCronExpression($expression, 0);
}
}
}

0 comments on commit 50a4bf7

Please sign in to comment.