Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
DiRule.php
Go to the documentation of this file.
1 <?php
9 
10 use DOMDocument;
11 use DOMXPath;
14 
15 class DiRule implements RuleInterface
16 {
20  private $mapper;
21 
25  private $pattern;
26 
30  public function __construct(VirtualTypeMapper $mapper)
31  {
32  $this->mapper = $mapper;
33  }
34 
39  private function getPattern()
40  {
41  if ($this->pattern === null) {
42  $this->pattern = '~\b(?<class>(?<module>('
43  . implode('[_\\\\]|', Files::init()->getNamespaces())
44  . '[_\\\\])[a-zA-Z0-9]+)[a-zA-Z0-9_\\\\]*)\b~';
45  }
46 
47  return $this->pattern;
48  }
49 
53  private static $tagNameMap = [
54  'type' => ['name'],
55  'preference' => [
56  'type',
57  'for'
58  ],
59  'plugin' => ['type'],
60  'virtualType' => ['type']
61  ];
62 
74  public function getDependencyInfo($currentModule, $fileType, $file, &$contents)
75  {
76  if (pathinfo($file, PATHINFO_BASENAME) !== 'di.xml') {
77  return [];
78  }
79 
80  $dependenciesInfo = [];
81  $scope = $this->mapper->getScopeFromFile($file);
82  foreach ($this->fetchPossibleDependencies($contents) as $type => $deps) {
83  foreach ($deps as $dep) {
84  $dep = $this->mapper->getType($dep, $scope);
85  if (preg_match($this->getPattern(), $dep, $matches)) {
86  $referenceModule = str_replace('_', '\\', $matches['module']);
87  if ($currentModule === $referenceModule) {
88  continue;
89  }
90  $dependenciesInfo[] = [
91  'module' => $referenceModule,
92  'type' => $type,
93  'source' => $matches['class'],
94  ];
95  }
96  }
97  }
98  return $dependenciesInfo;
99  }
100 
105  private function fetchPossibleDependencies($contents)
106  {
107  $doc = new DOMDocument();
108  $doc->loadXML($contents);
109  return [
110  RuleInterface::TYPE_SOFT => $this->getSoftDependencies($doc),
111  RuleInterface::TYPE_HARD => $this->getHardDependencies($doc)
112  ];
113  }
114 
119  private function getSoftDependencies(DOMDocument $doc)
120  {
121  $result = [];
122  foreach (self::$tagNameMap as $tagName => $attributeNames) {
123  $nodes = $doc->getElementsByTagName($tagName);
125  foreach ($nodes as $node) {
126  foreach ($attributeNames as $attributeName) {
127  $result[] = $node->getAttribute($attributeName);
128  }
129  }
130  }
131 
132  return $result;
133  }
134 
139  private function getHardDependencies(DOMDocument $doc)
140  {
141  $result = [];
142  $xpath = new DOMXPath($doc);
143  $textNodes = $xpath->query('//*[@xsi:type="object"]');
145  foreach ($textNodes as $node) {
146  $result[] = $node->nodeValue;
147  }
148 
149  return $result;
150  }
151 }
__construct(VirtualTypeMapper $mapper)
Definition: DiRule.php:30
$contents
Definition: website.php:14
$type
Definition: item.phtml:13
getDependencyInfo($currentModule, $fileType, $file, &$contents)
Definition: DiRule.php:74