Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
ObserverImplementationTest.php
Go to the documentation of this file.
1 <?php
6 namespace Magento\Test\Integrity;
7 
9 
13 class ObserverImplementationTest extends \PHPUnit\Framework\TestCase
14 {
18  const OBSERVER_INTERFACE = \Magento\Framework\Event\ObserverInterface::class;
19 
23  protected static $observerClasses = [];
24 
25  public static function setUpBeforeClass()
26  {
27  self::$observerClasses = array_merge(
28  self::getObserverClasses('{*/events.xml,events.xml}', '//observer')
29  );
30  }
31 
33  {
34  $errors = [];
35  foreach (self::$observerClasses as $observerClass) {
36  if (!is_subclass_of($observerClass, self::OBSERVER_INTERFACE)) {
37  $errors[] = $observerClass;
38  }
39  }
40 
41  if ($errors) {
42  $errors = array_unique($errors);
43  sort($errors);
44  $this->fail(
45  sprintf(
46  '%d of observers which not implement \Magento\Framework\Event\ObserverInterface: %s',
47  count($errors),
48  "\n" . implode("\n", $errors)
49  )
50  );
51  }
52  }
53 
55  {
56  $errors = [];
57  foreach (self::$observerClasses as $observerClass) {
58  $reflection = (new \ReflectionClass($observerClass));
59  $maxCountMethod = $reflection->getConstructor() ? 2 : 1;
60 
61  if (count($reflection->getMethods(\ReflectionMethod::IS_PUBLIC)) > $maxCountMethod) {
62  $errors[] = $observerClass;
63  }
64  }
65 
66  if ($errors) {
67  $errors = array_unique($errors);
68  sort($errors);
69  $this->fail(
70  sprintf(
71  '%d of observers have extra public methods: %s',
72  count($errors),
73  implode("\n", $errors)
74  )
75  );
76  }
77  }
78 
84  protected static function getObserverClasses($fileNamePattern, $xpath)
85  {
86  $observerClasses = [];
87  foreach (Files::init()->getConfigFiles($fileNamePattern, [], false) as $configFile) {
88  foreach (simplexml_load_file($configFile)->xpath($xpath) as $observer) {
89  $className = (string)$observer->attributes()->instance;
90  // $className may be empty in cases like this <observer name="observer_name" disabled="true" />
91  if ($className) {
92  $observerClasses[] = trim((string)$observer->attributes()->instance, '\\');
93  }
94  }
95  }
96 
97  $blacklistFiles = str_replace('\\', '/', realpath(__DIR__)) . '/_files/blacklist/observers*.txt';
98  $blacklistExceptions = [];
99  foreach (glob($blacklistFiles) as $fileName) {
100  $blacklistExceptions = array_merge(
101  $blacklistExceptions,
102  file($fileName, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)
103  );
104  }
105  return array_diff(
106  array_unique($observerClasses),
107  $blacklistExceptions
108  );
109  }
110 }
is_subclass_of($obj, $className)
defined('TESTS_BP')||define('TESTS_BP' __DIR__
Definition: _bootstrap.php:60
$fileName
Definition: translate.phtml:15
$errors
Definition: overview.phtml:9
if($currentSelectedMethod==$_code) $className
Definition: form.phtml:31