Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
DuplicateNodeValidationUtil.php
Go to the documentation of this file.
1 <?php
8 
11 
17 {
22  private $uniqueKey;
23 
28  private $exceptionCollector;
29 
35  public function __construct($uniqueKey, $exceptionCollector)
36  {
37  $this->uniqueKey = $uniqueKey;
38  $this->exceptionCollector = $exceptionCollector;
39  }
40 
48  public function validateChildUniqueness(\DOMElement $parentNode, $filename, $parentKey)
49  {
50  $childNodes = $parentNode->childNodes;
51  $type = ucfirst($parentNode->tagName);
52 
53  $keyValues = [];
54  for ($i = 0; $i < $childNodes->length; $i++) {
55  $currentNode = $childNodes->item($i);
56 
57  if (!is_a($currentNode, \DOMElement::class)) {
58  continue;
59  }
60 
61  if ($currentNode->hasAttribute($this->uniqueKey)) {
62  $keyValues[] = $currentNode->getAttribute($this->uniqueKey);
63  }
64  }
65 
66  $withoutDuplicates = array_unique($keyValues);
67 
68  if (count($withoutDuplicates) != count($keyValues)) {
69  $duplicates = array_diff_assoc($keyValues, $withoutDuplicates);
70  $keyError = "";
71  foreach ($duplicates as $duplicateKey => $duplicateValue) {
72  $keyError .= "\t{$this->uniqueKey}: {$duplicateValue} is used more than once.";
73  if ($parentKey !== null) {
74  $keyError .=" (Parent: {$parentKey})";
75  }
76  $keyError .= "\n";
77  }
78 
79  $errorMsg = "{$type} cannot use {$this->uniqueKey}s more than once.\t\n{$keyError}\tin file: {$filename}";
80  $this->exceptionCollector->addError($filename, $errorMsg);
81  }
82  }
83 }
$type
Definition: item.phtml:13
$i
Definition: gallery.phtml:31