Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
AbstractCondition.php
Go to the documentation of this file.
1 <?php
8 
11 
24 {
29  protected $_inputType = null;
30 
35  protected $_defaultOperatorOptions = null;
36 
41  protected $_defaultOperatorInputByType = null;
42 
47  protected $_arrayInputTypes = [];
48 
52  protected $_assetRepo;
53 
57  protected $_localeDate;
58 
62  protected $_layout;
63 
68  protected $elementName = 'rule';
69 
74  public function __construct(Context $context, array $data = [])
75  {
76  $this->_assetRepo = $context->getAssetRepository();
77  $this->_localeDate = $context->getLocaleDate();
78  $this->_layout = $context->getLayout();
79 
80  parent::__construct($data);
81 
82  $this->loadAttributeOptions()->loadOperatorOptions()->loadValueOptions();
83 
84  $options = $this->getAttributeOptions();
85  if ($options) {
86  reset($options);
87  $this->setAttribute(key($options));
88  }
89  $options = $this->getOperatorOptions();
90  if ($options) {
91  reset($options);
92  $this->setOperator(key($options));
93  }
94  }
95 
102  {
103  if (null === $this->_defaultOperatorInputByType) {
104  $this->_defaultOperatorInputByType = [
105  'string' => ['==', '!=', '>=', '>', '<=', '<', '{}', '!{}', '()', '!()'],
106  'numeric' => ['==', '!=', '>=', '>', '<=', '<', '()', '!()'],
107  'date' => ['==', '>=', '<='],
108  'select' => ['==', '!='],
109  'boolean' => ['==', '!='],
110  'multiselect' => ['{}', '!{}', '()', '!()'],
111  'grid' => ['()', '!()'],
112  ];
113  $this->_arrayInputTypes = ['multiselect', 'grid'];
114  }
116  }
117 
124  public function getDefaultOperatorOptions()
125  {
126  if (null === $this->_defaultOperatorOptions) {
127  $this->_defaultOperatorOptions = [
128  '==' => __('is'),
129  '!=' => __('is not'),
130  '>=' => __('equals or greater than'),
131  '<=' => __('equals or less than'),
132  '>' => __('greater than'),
133  '<' => __('less than'),
134  '{}' => __('contains'),
135  '!{}' => __('does not contain'),
136  '()' => __('is one of'),
137  '!()' => __('is not one of'),
138  ];
139  }
141  }
142 
146  public function getForm()
147  {
148  return $this->getRule()->getForm();
149  }
150 
156  public function asArray(array $arrAttributes = [])
157  {
158  return [
159  'type' => $this->getType(),
160  'attribute' => $this->getAttribute(),
161  'operator' => $this->getOperator(),
162  'value' => $this->getValue(),
163  'is_value_processed' => $this->getIsValueParsed(),
164  ];
165  }
166 
172  public function getTablesToJoin()
173  {
174  return [];
175  }
176 
182  public function getBindArgumentValue()
183  {
184  return $this->getValueParsed();
185  }
186 
192  public function getMappedSqlField()
193  {
194  return $this->getAttribute();
195  }
196 
200  public function asXml()
201  {
202  return "<type>" .
203  $this->getType() .
204  "</type>" .
205  "<attribute>" .
206  $this->getAttribute() .
207  "</attribute>" .
208  "<operator>" .
209  $this->getOperator() .
210  "</operator>" .
211  "<value>" .
212  $this->getValue() .
213  "</value>";
214  }
215 
221  public function loadArray($arr)
222  {
223  $this->setType($arr['type']);
224  $this->setAttribute(isset($arr['attribute']) ? $arr['attribute'] : false);
225  $this->setOperator(isset($arr['operator']) ? $arr['operator'] : false);
226  $this->setValue(isset($arr['value']) ? $arr['value'] : false);
227  $this->setIsValueParsed(isset($arr['is_value_parsed']) ? $arr['is_value_parsed'] : false);
228  return $this;
229  }
230 
235  public function loadXml($xml)
236  {
237  if (is_string($xml)) {
238  $xml = simplexml_load_string($xml);
239  }
240  $this->loadArray((array)$xml);
241  return $this;
242  }
243 
247  public function loadAttributeOptions()
248  {
249  return $this;
250  }
251 
255  public function getAttributeOptions()
256  {
257  return [];
258  }
259 
263  public function getAttributeSelectOptions()
264  {
265  $opt = [];
266  foreach ($this->getAttributeOption() as $key => $value) {
267  $opt[] = ['value' => $key, 'label' => $value];
268  }
269  return $opt;
270  }
271 
275  public function getAttributeName()
276  {
277  return $this->getAttributeOption($this->getAttribute());
278  }
279 
283  public function loadOperatorOptions()
284  {
285  $this->setOperatorOption($this->getDefaultOperatorOptions());
286  $this->setOperatorByInputType($this->getDefaultOperatorInputByType());
287  return $this;
288  }
289 
297  public function getInputType()
298  {
299  return null === $this->_inputType ? 'string' : $this->_inputType;
300  }
301 
305  public function getOperatorSelectOptions()
306  {
307  $type = $this->getInputType();
308  $opt = [];
309  $operatorByType = $this->getOperatorByInputType();
310  foreach ($this->getOperatorOption() as $key => $value) {
311  if (!$operatorByType || in_array($key, $operatorByType[$type])) {
312  $opt[] = ['value' => $key, 'label' => $value];
313  }
314  }
315  return $opt;
316  }
317 
321  public function getOperatorName()
322  {
323  return $this->getOperatorOption($this->getOperator());
324  }
325 
329  public function loadValueOptions()
330  {
331  $this->setValueOption([]);
332  return $this;
333  }
334 
338  public function getValueSelectOptions()
339  {
340  $opt = [];
341  if ($this->hasValueOption()) {
342  foreach ((array)$this->getValueOption() as $key => $value) {
343  $opt[] = ['value' => $key, 'label' => $value];
344  }
345  }
346  return $opt;
347  }
348 
354  public function getValueParsed()
355  {
356  if (!$this->hasValueParsed()) {
357  $value = $this->getData('value');
358  if (is_array($value) && count($value) === 1) {
359  $value = reset($value);
360  }
361  if (!is_array($value) && $this->isArrayOperatorType() && $value) {
362  $value = preg_split('#\s*[,;]\s*#', $value, null, PREG_SPLIT_NO_EMPTY);
363  }
364  $this->setValueParsed($value);
365  }
366  return $this->getData('value_parsed');
367  }
368 
376  public function isArrayOperatorType()
377  {
378  $operator = $this->getOperator();
379  return $operator === '()' || $operator === '!()' || in_array($this->getInputType(), $this->_arrayInputTypes);
380  }
381 
385  public function getValue()
386  {
387  if ($this->getInputType() == 'date' && !$this->getIsValueParsed()) {
388  // date format intentionally hard-coded
389  $this->setValue(
390  (new \DateTime($this->getData('value')))->format('Y-m-d H:i:s')
391  );
392  $this->setIsValueParsed(true);
393  }
394  return $this->getData('value');
395  }
396 
401  public function getValueName()
402  {
403  $value = $this->getValue();
404  if ($value === null || '' === $value) {
405  return '...';
406  }
407 
408  $options = $this->getValueSelectOptions();
409  $valueArr = [];
410  if (!empty($options)) {
411  foreach ($options as $option) {
412  if (is_array($value)) {
413  if (in_array($option['value'], $value)) {
414  $valueArr[] = $option['label'];
415  }
416  } elseif (isset($option['value'])) {
417  if (is_array($option['value'])) {
418  foreach ($option['value'] as $optionValue) {
419  if ($optionValue['value'] == $value) {
420  return $optionValue['label'];
421  }
422  }
423  }
424  if ($option['value'] == $value) {
425  return $option['label'];
426  }
427  }
428  }
429  }
430  if (!empty($valueArr)) {
431  $value = implode(', ', $valueArr);
432  } elseif (is_array($value)) {
433  $value = implode(', ', $value);
434  }
435  return $value;
436  }
437 
443  public function getNewChildSelectOptions()
444  {
445  return [['value' => '', 'label' => __('Please choose a condition to add.')]];
446  }
447 
451  public function getNewChildName()
452  {
453  return $this->getAddLinkHtml();
454  }
455 
459  public function asHtml()
460  {
461  return $this->getTypeElementHtml() .
462  $this->getAttributeElementHtml() .
463  $this->getOperatorElementHtml() .
464  $this->getValueElementHtml() .
465  $this->getRemoveLinkHtml() .
466  $this->getChooserContainerHtml();
467  }
468 
472  public function asHtmlRecursive()
473  {
474  return $this->asHtml();
475  }
476 
480  public function getTypeElement()
481  {
482  return $this->getForm()->addField(
483  $this->getPrefix() . '__' . $this->getId() . '__type',
484  'hidden',
485  [
486  'name' => $this->elementName . '[' . $this->getPrefix() . '][' . $this->getId() . '][type]',
487  'value' => $this->getType(),
488  'no_span' => true,
489  'class' => 'hidden',
490  'data-form-part' => $this->getFormName()
491  ]
492  );
493  }
494 
498  public function getTypeElementHtml()
499  {
500  return $this->getTypeElement()->getHtml();
501  }
502 
506  public function getAttributeElement()
507  {
508  if (null === $this->getAttribute()) {
509  $options = $this->getAttributeOption();
510  if ($options) {
511  reset($options);
512  $this->setAttribute(key($options));
513  }
514  }
515  return $this->getForm()->addField(
516  $this->getPrefix() . '__' . $this->getId() . '__attribute',
517  'select',
518  [
519  'name' => $this->elementName . '[' . $this->getPrefix() . '][' . $this->getId() . '][attribute]',
520  'values' => $this->getAttributeSelectOptions(),
521  'value' => $this->getAttribute(),
522  'value_name' => $this->getAttributeName(),
523  'data-form-part' => $this->getFormName()
524  ]
525  )->setRenderer(
526  $this->_layout->getBlockSingleton(\Magento\Rule\Block\Editable::class)
527  );
528  }
529 
533  public function getAttributeElementHtml()
534  {
535  return $this->getAttributeElement()->getHtml();
536  }
537 
544  public function getOperatorElement()
545  {
547  if ($this->getOperator() === null) {
548  $option = reset($options);
549  $this->setOperator($option['value']);
550  }
551 
552  $elementId = sprintf('%s__%s__operator', $this->getPrefix(), $this->getId());
553  $elementName = sprintf($this->elementName . '[%s][%s][operator]', $this->getPrefix(), $this->getId());
554  $element = $this->getForm()->addField(
555  $elementId,
556  'select',
557  [
558  'name' => $elementName,
559  'values' => $options,
560  'value' => $this->getOperator(),
561  'value_name' => $this->getOperatorName(),
562  'data-form-part' => $this->getFormName()
563  ]
564  );
565  $element->setRenderer($this->_layout->getBlockSingleton(\Magento\Rule\Block\Editable::class));
566 
567  return $element;
568  }
569 
573  public function getOperatorElementHtml()
574  {
575  return $this->getOperatorElement()->getHtml();
576  }
577 
584  public function getValueElementType()
585  {
586  return 'text';
587  }
588 
592  public function getValueElementRenderer()
593  {
594  if (strpos($this->getValueElementType(), '/') !== false) {
595  return $this->_layout->getBlockSingleton($this->getValueElementType());
596  }
597  return $this->_layout->getBlockSingleton(\Magento\Rule\Block\Editable::class);
598  }
599 
603  public function getValueElement()
604  {
605  $elementParams = [
606  'name' => $this->elementName . '[' . $this->getPrefix() . '][' . $this->getId() . '][value]',
607  'value' => $this->getValue(),
608  'values' => $this->getValueSelectOptions(),
609  'value_name' => $this->getValueName(),
610  'after_element_html' => $this->getValueAfterElementHtml(),
611  'explicit_apply' => $this->getExplicitApply(),
612  'data-form-part' => $this->getFormName()
613  ];
614  if ($this->getInputType() == 'date') {
615  // date format intentionally hard-coded
616  $elementParams['input_format'] = \Magento\Framework\Stdlib\DateTime::DATE_INTERNAL_FORMAT;
617  $elementParams['date_format'] = \Magento\Framework\Stdlib\DateTime::DATE_INTERNAL_FORMAT;
618  }
619  return $this->getForm()->addField(
620  $this->getPrefix() . '__' . $this->getId() . '__value',
621  $this->getValueElementType(),
622  $elementParams
623  )->setRenderer(
624  $this->getValueElementRenderer()
625  );
626  }
627 
631  public function getValueElementHtml()
632  {
633  return $this->getValueElement()->getHtml();
634  }
635 
639  public function getAddLinkHtml()
640  {
641  $src = $this->_assetRepo->getUrl('images/rule_component_add.gif');
642  return '<img src="' . $src . '" class="rule-param-add v-middle" alt="" title="' . __('Add') . '"/>';
643  }
644 
648  public function getRemoveLinkHtml()
649  {
650  $src = $this->_assetRepo->getUrl('images/rule_component_remove.gif');
651  $html = ' <span class="rule-param"><a href="javascript:void(0)" class="rule-param-remove" title="' . __(
652  'Remove'
653  ) . '"><img src="' . $src . '" alt="" class="v-middle" /></a></span>';
654  return $html;
655  }
656 
660  public function getChooserContainerHtml()
661  {
662  $url = $this->getValueElementChooserUrl();
663  return $url ? '<div class="rule-chooser" url="' . $url . '"></div>' : '';
664  }
665 
671  public function asString($format = '')
672  {
673  return $this->getAttributeName() . ' ' . $this->getOperatorName() . ' ' . $this->getValueName();
674  }
675 
680  public function asStringRecursive($level = 0)
681  {
682  return str_pad('', $level * 3, ' ', STR_PAD_LEFT) . $this->asString();
683  }
684 
694  public function validateAttribute($validatedValue)
695  {
696  if (is_object($validatedValue)) {
697  return false;
698  }
699 
703  $value = $this->getValueParsed();
704 
708  $option = $this->getOperatorForValidate();
709 
710  // if operator requires array and it is not, or on opposite, return false
711  if ($this->isArrayOperatorType() xor is_array($value)) {
712  return false;
713  }
714 
715  $result = false;
716 
717  switch ($option) {
718  case '==':
719  case '!=':
720  if (is_array($value)) {
721  if (!is_array($validatedValue)) {
722  return false;
723  }
724  $result = !empty(array_intersect($value, $validatedValue));
725  } else {
726  if (is_array($validatedValue)) {
727  $result = count($validatedValue) == 1 && array_shift($validatedValue) == $value;
728  } else {
729  $result = $this->_compareValues($validatedValue, $value);
730  }
731  }
732  break;
733 
734  case '<=':
735  case '>':
736  if (!is_scalar($validatedValue)) {
737  return false;
738  }
739  $result = $validatedValue <= $value;
740  break;
741 
742  case '>=':
743  case '<':
744  if (!is_scalar($validatedValue)) {
745  return false;
746  }
747  $result = $validatedValue >= $value;
748  break;
749 
750  case '{}':
751  case '!{}':
752  if (is_scalar($validatedValue) && is_array($value)) {
753  foreach ($value as $item) {
754  if (stripos($validatedValue, (string)$item) !== false) {
755  $result = true;
756  break;
757  }
758  }
759  } elseif (is_array($value)) {
760  if (!is_array($validatedValue)) {
761  return false;
762  }
763  $result = array_intersect($value, $validatedValue);
764  $result = !empty($result);
765  } else {
766  if (is_array($validatedValue)) {
767  $result = in_array($value, $validatedValue);
768  } else {
769  $result = $this->_compareValues($value, $validatedValue, false);
770  }
771  }
772  break;
773 
774  case '()':
775  case '!()':
776  if (is_array($validatedValue)) {
777  $result = count(array_intersect($validatedValue, (array)$value)) > 0;
778  } else {
779  $value = (array)$value;
780  foreach ($value as $item) {
781  if ($this->_compareValues($validatedValue, $item)) {
782  $result = true;
783  break;
784  }
785  }
786  }
787  break;
788  }
789 
790  if ('!=' == $option || '>' == $option || '<' == $option || '!{}' == $option || '!()' == $option) {
791  $result = !$result;
792  }
793 
794  return $result;
795  }
796 
805  protected function _compareValues($validatedValue, $value, $strict = true)
806  {
807  if ($strict && is_numeric($validatedValue) && is_numeric($value)) {
808  return $validatedValue == $value;
809  }
810 
811  $validatePattern = preg_quote($validatedValue, '~');
812  if ($strict) {
813  $validatePattern = '^' . $validatePattern . '$';
814  }
815  return (bool)preg_match('~' . $validatePattern . '~iu', $value);
816  }
817 
822  public function validate(\Magento\Framework\Model\AbstractModel $model)
823  {
824  if (!$model->hasData($this->getAttribute())) {
825  $model->load($model->getId());
826  }
827  $attributeValue = $model->getData($this->getAttribute());
828 
829  return $this->validateAttribute($attributeValue);
830  }
831 
837  public function getOperatorForValidate()
838  {
839  return $this->getOperator();
840  }
841 }
getData($key='', $index=null)
Definition: DataObject.php:119
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17
__construct(Context $context, array $data=[])
__()
Definition: __.php:13
$type
Definition: item.phtml:13
$value
Definition: gender.phtml:16
$format
Definition: list.phtml:12
validate(\Magento\Framework\Model\AbstractModel $model)
_compareValues($validatedValue, $value, $strict=true)
$element
Definition: element.phtml:12