ExampleDataLoader - Fix loading data-sets from `tests/phpunit/*` from web-env
authorTim Otten <totten@civicrm.org>
Wed, 15 Sep 2021 00:11:01 +0000 (17:11 -0700)
committerTim Otten <totten@civicrm.org>
Wed, 15 Sep 2021 00:18:17 +0000 (17:18 -0700)
Before: If you add example-data under `tests/phpunit/`, then it works
in headless env. In web-env, it will be scanned, but the `include $file` step will fail.

After: The `include $file` step will succeed.

Civi/Test/ExampleDataLoader.php

index 68a0443bc70c64a26bba606ea3d62661bd6f85e5..8b78d82353623ac9540b072e7c432fd03987283d 100644 (file)
@@ -112,17 +112,24 @@ class ExampleDataLoader {
    * @param $classDelim
    *   Namespace separator, eg underscore or backslash.
    * @return array
-   *   Array(string $relativeFileName => string $className).
+   *   Array(string $includeFile => string $className).
    */
   private function scanExampleClasses($classRoot, $classDir, $classDelim): array {
+    $civiRoot = \Civi::paths()->getPath('[civicrm.root]/');
+    $classRoot = \CRM_Utils_File::addTrailingSlash($classRoot, '/');
+    // Prefer include-paths relative to civiRoot - eg make tests/phpunit/* loadable at runtime.
+    $includeRoot = \CRM_Utils_File::isChildPath($civiRoot, $classRoot) ? $civiRoot : $classRoot;
+
     $r = [];
     $exDirs = (array) glob($classRoot . $classDir);
     foreach ($exDirs as $exDir) {
       foreach (\CRM_Utils_File::findFiles($exDir, '*.ex.php') as $file) {
         $file = str_replace(DIRECTORY_SEPARATOR, '/', $file);
-        $file = \CRM_Utils_File::relativize($file, \CRM_Utils_File::addTrailingSlash($classRoot, '/'));
-        $class = str_replace('/', $classDelim, preg_replace('/\.ex\.php$/', '', $file));
-        $r[$file] = $class;
+        $includeFile = \CRM_Utils_File::relativize($file, $includeRoot);
+        $classFile = \CRM_Utils_File::relativize($file, $classRoot);
+        $class = str_replace('/', $classDelim, preg_replace('/\.ex\.php$/', '',
+          $classFile));
+        $r[$includeFile] = $class;
       }
     }
     return $r;