Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Cron.php
Go to the documentation of this file.
1 <?php
13 
14 class Cron extends \Magento\Framework\Event\Observer
15 {
25  public function isValidFor(\Magento\Framework\Event $event)
26  {
27  $e = preg_split('#\s+#', $this->getCronExpr(), null, PREG_SPLIT_NO_EMPTY);
28  if (sizeof($e) !== 5) {
29  return false;
30  }
31 
32  $d = getdate($this->getNow());
33 
34  return $this->matchCronExpression(
35  $e[0],
36  $d['minutes']
37  ) && $this->matchCronExpression(
38  $e[1],
39  $d['hours']
40  ) && $this->matchCronExpression(
41  $e[2],
42  $d['mday']
43  ) && $this->matchCronExpression(
44  $e[3],
45  $d['mon']
46  ) && $this->matchCronExpression(
47  $e[4],
48  $d['wday']
49  );
50  }
51 
55  public function getNow()
56  {
57  if (!$this->hasNow()) {
58  $this->setNow(time());
59  }
60  return $this->getData('now');
61  }
62 
70  public function matchCronExpression($expr, $num)
71  {
72  // handle ALL match
73  if ($expr === '*') {
74  return true;
75  }
76 
77  // handle multiple options
78  if (strpos($expr, ',') !== false) {
79  foreach (explode(',', $expr) as $e) {
80  if ($this->matchCronExpression($e, $num)) {
81  return true;
82  }
83  }
84  return false;
85  }
86 
87  // handle modulus
88  if (strpos($expr, '/') !== false) {
89  $e = explode('/', $expr);
90  if (sizeof($e) !== 2) {
91  return false;
92  }
93  $expr = $e[0];
94  $mod = $e[1];
95  if (!is_numeric($mod)) {
96  return false;
97  }
98  } else {
99  $mod = 1;
100  }
101 
102  // handle range
103  if (strpos($expr, '-') !== false) {
104  $e = explode('-', $expr);
105  if (sizeof($e) !== 2) {
106  return false;
107  }
108 
109  $from = $this->getNumeric($e[0]);
110  $to = $this->getNumeric($e[1]);
111 
112  return $from !== false && $to !== false && $num >= $from && $num <= $to && $num % $mod === 0;
113  }
114 
115  // handle regular token
116  $value = $this->getNumeric($expr);
117  return $value !== false && $num == $value && $num % $mod === 0;
118  }
119 
124  public function getNumeric($value)
125  {
126  static $data = [
127  'jan' => 1,
128  'feb' => 2,
129  'mar' => 3,
130  'apr' => 4,
131  'may' => 5,
132  'jun' => 6,
133  'jul' => 7,
134  'aug' => 8,
135  'sep' => 9,
136  'oct' => 10,
137  'nov' => 11,
138  'dec' => 12,
139  'sun' => 0,
140  'mon' => 1,
141  'tue' => 2,
142  'wed' => 3,
143  'thu' => 4,
144  'fri' => 5,
145  'sat' => 6,
146  ];
147 
148  if (is_numeric($value)) {
149  return $value;
150  }
151 
152  if (is_string($value)) {
153  $value = strtolower(substr($value, 0, 3));
154  if (isset($data[$value])) {
155  return $data[$value];
156  }
157  }
158 
159  return false;
160  }
161 }
getData($key='', $index=null)
Definition: DataObject.php:119
$value
Definition: gender.phtml:16
isValidFor(\Magento\Framework\Event $event)
Definition: Cron.php:25