Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
ComponentRegistrarFixture.php
Go to the documentation of this file.
1 <?php
8 
9 use RecursiveDirectoryIterator;
10 use RecursiveIteratorIterator;
11 use RegexIterator;
12 
17 {
21  const ANNOTATION_NAME = 'magentoComponentsDir';
22 
26  const REGISTRAR_CLASS = \Magento\Framework\Component\ComponentRegistrar::class;
27  const PATHS_FIELD = 'paths';
35  private $fixtureBaseDir;
36 
42  private $origComponents = null;
43 
49  public function __construct($fixtureBaseDir)
50  {
51  $this->fixtureBaseDir = $fixtureBaseDir;
52  }
53 
60  public function startTest(\PHPUnit\Framework\TestCase $test)
61  {
62  $this->registerComponents($test);
63  }
64 
73  public function endTest(\PHPUnit\Framework\TestCase $test)
74  {
75  $this->restoreComponents();
76  }
77 
83  private function registerComponents(\PHPUnit\Framework\TestCase $test)
84  {
85  $annotations = $test->getAnnotations();
86  $componentAnnotations = [];
87  if (isset($annotations['class'][self::ANNOTATION_NAME])) {
88  $componentAnnotations = array_merge($componentAnnotations, $annotations['class'][self::ANNOTATION_NAME]);
89  }
90  if (isset($annotations['method'][self::ANNOTATION_NAME])) {
91  $componentAnnotations = array_merge($componentAnnotations, $annotations['method'][self::ANNOTATION_NAME]);
92  }
93  if (empty($componentAnnotations)) {
94  return;
95  }
96  $componentAnnotations = array_unique($componentAnnotations);
97  $reflection = new \ReflectionClass(self::REGISTRAR_CLASS);
98  $paths = $reflection->getProperty(self::PATHS_FIELD);
99  $paths->setAccessible(true);
100  $this->origComponents = $paths->getValue();
101  $paths->setAccessible(false);
102  foreach ($componentAnnotations as $fixturePath) {
103  $fixturesDir = $this->fixtureBaseDir . '/' . $fixturePath;
104  if (!file_exists($fixturesDir)) {
105  throw new \InvalidArgumentException(
106  self::ANNOTATION_NAME . " fixture '$fixturePath' does not exist"
107  );
108  }
109  $iterator = new RegexIterator(
110  new RecursiveIteratorIterator(
111  new RecursiveDirectoryIterator($fixturesDir, \FilesystemIterator::SKIP_DOTS)
112  ),
113  '/^.+\/registration\.php$/'
114  );
118  foreach ($iterator as $registrationFile) {
119  require $registrationFile->getRealPath();
120  }
121  }
122  }
123 
127  private function restoreComponents()
128  {
129  if (null !== $this->origComponents) {
130  $reflection = new \ReflectionClass(self::REGISTRAR_CLASS);
131  $paths = $reflection->getProperty(self::PATHS_FIELD);
132  $paths->setAccessible(true);
133  $paths->setValue($this->origComponents);
134  $paths->setAccessible(false);
135  $this->origComponents = null;
136  }
137  }
138 }
$paths
Definition: _bootstrap.php:83