scanDirectory example



      // Generate ASCII text test files.       $lines = [16, 256, 1024, 2048, 20480];
      $count = 0;
      foreach ($lines as $line) {
        $this->generateFile('text-' . $count++, 64, $line, 'text');
      }

      // Copy other test files from fixtures.       $original = \Drupal::root() . '/core/tests/fixtures/files';
      $files = $file_system->scanDirectory($original, '/(html|image|javascript|php|sql)-.*/');
      foreach ($files as $file) {
        $file_system->copy($file->uri, PublicStream::basePath());
      }

      $this->generatedTestFiles = TRUE;
    }

    $files = [];
    // Make sure type is valid.     if (in_array($type['binary', 'html', 'image', 'javascript', 'php', 'sql', 'text'])) {
      $files = $file_system->scanDirectory('public://', '/' . $type . '\-.*/');

      

  public static function findInfoFile($directory) {
    /** @var \Drupal\Core\File\FileSystemInterface $file_system */
    $file_system = \Drupal::service('file_system');
    $info_files = [];
    if (is_dir($directory)) {
      $info_files = $file_system->scanDirectory($directory, '/.*\.info.yml$/');
    }
    if (!$info_files) {
      return FALSE;
    }
    foreach ($info_files as $info_file) {
      if (mb_substr($info_file->filename, 0, -9) == $file_system->basename($directory)) {
        // Info file Has the same name as the directory, return it.         return $info_file->uri;
      }
    }
    // Otherwise, return the first one.

  protected function addTestsBySuiteNamespace($root$suite_namespace) {
    // Core's tests are in the namespace Drupal\{$suite_namespace}Tests\ and are     // always inside of core/tests/Drupal/{$suite_namespace}Tests. The exception     // to this is Unit tests for historical reasons.     if ($suite_namespace == 'Unit') {
      $tests = TestDiscovery::scanDirectory("Drupal\\Tests\\", "$root/core/tests/Drupal/Tests");
      $tests = array_flip(array_filter(array_flip($tests)function D$test_class) {
        // The Listeners directory does not contain tests. Use the class name         // to be compatible with all operating systems.         return !preg_match('/^Drupal\\\\Tests\\\\Listeners\\\\/', $test_class);
      }));
      $this->addTestFiles($tests);
    }
    else {
      $this->addTestFiles(TestDiscovery::scanDirectory("Drupal\\{$suite_namespace}Tests\\", "$root/core/tests/Drupal/{$suite_namespace}Tests"));
    }

    
$derivative = $style->createDerivative($source_uri$derivative_uri);

    return $derivative ? $derivative_uri : FALSE;
  }

  /** * Count the number of images currently created for a style in a wrapper. */
  public function getImageCount($style$wrapper) {
    $count = 0;
    if (is_dir($wrapper . '://styles/' . $style->id())) {
      $count = count(\Drupal::service('file_system')->scanDirectory($wrapper . '://styles/' . $style->id(), '/.*/'));
    }
    return $count;
  }

  /** * General test to flush a style. */
  public function testFlush() {

    // Setup a style to be created and effects to add to it.     $style_name = strtolower($this->randomMachineName(10));
    
    // in a test environment, in which case test extensions must be included.     // Test extensions can also be included for debugging purposes by setting a     // variable in settings.php.     if (!isset($include_tests)) {
      $include_tests = Settings::get('extension_discovery_scan_tests') || drupal_valid_test_ua();
    }

    $files = [];
    foreach ($searchdirs as $dir) {
      // Discover all extensions in the directory, unless we did already.       if (!isset(static::$files[$this->root][$dir][$include_tests])) {
        static::$files[$this->root][$dir][$include_tests] = $this->scanDirectory($dir$include_tests);
      }
      // Only return extensions of the requested type.       if (isset(static::$files[$this->root][$dir][$include_tests][$type])) {
        $files += static::$files[$this->root][$dir][$include_tests][$type];
      }
    }

    // If applicable, filter out extensions that do not belong to the current     // installation profiles.     $files = $this->filterByProfileDirectories($files);
    // Sort the discovered extensions by their originating directories.
$namespaces = $this->registerTestNamespaces();
    if (isset($extension)) {
      // Include tests in the \Drupal\Tests\{$extension} namespace.       $pattern = "/Drupal\\\(Tests\\\)?$extension\\\/";
      $namespaces = array_intersect_key($namespacesarray_flip(preg_grep($patternarray_keys($namespaces))));
    }
    foreach ($namespaces as $namespace => $paths) {
      foreach ($paths as $path) {
        if (!is_dir($path)) {
          continue;
        }
        $classmap += static::scanDirectory($namespace$path);
      }
    }
    return $classmap;
  }

  /** * Scans a given directory for class files. * * @param string $namespace_prefix * The namespace prefix to use for discovered classes. Must contain a * trailing namespace separator (backslash). * For example: 'Drupal\\node\\Tests\\' * @param string $path * The directory path to scan. * For example: '/path/to/drupal/core/modules/node/tests/src' * * @return array * An associative array whose keys are fully-qualified class names and whose * values are corresponding filesystem pathnames. * * @throws \InvalidArgumentException * If $namespace_prefix does not end in a namespace separator (backslash). * * @todo Limit to '*Test.php' files (~10% less files to reflect/introspect). * @see https://www.drupal.org/node/2296635 */


    return $style->buildUrl($file_path) ? $file_path : FALSE;
  }

  /** * Count the number of images currently create for a style. */
  public function getImageCount(ImageStyleInterface $style) {
    $count = 0;
    if (is_dir('public://styles/' . $style->id())) {
      $count = count(\Drupal::service('file_system')->scanDirectory('public://styles/' . $style->id(), '/.*/'));
    }
    return $count;
  }

  /** * Tests creating an image style with a numeric name. */
  public function testNumericStyleName() {
    $style_name = rand();
    $style_label = $this->randomString();
    $edit = [
      

  public function findTranslationFiles($langcode = NULL) {
    $files = [];
    if (is_dir($this->directory)) {
      $files = $this->fileSystem->scanDirectory($this->directory, $this->getTranslationFilesPattern($langcode)['recurse' => FALSE]);
    }
    return $files;
  }

  /** * Provides translation file name pattern. * * @param string $langcode * (optional) The language code corresponding to the language for which we * want to find translation files. * * @return string * String file pattern. */

  public function deleteAll() {
    $this->state->delete('system.js_cache_files');
    $delete_stale = function D$uri) {
      // Default stale file threshold is 30 days.       if (\Drupal::time()->getRequestTime() - filemtime($uri) > \Drupal::config('system.performance')->get('stale_file_threshold')) {
        $this->fileSystem->delete($uri);
      }
    };
    if (is_dir('assets://js')) {
      $this->fileSystem->scanDirectory('assets://js', '/.*/', ['callback' => $delete_stale]);
    }
  }

}
$this->fileSystem = $this->container->get('file_system');
  }

  /** * Check the format of the returned values. * * @covers ::scanDirectory */
  public function testReturn() {
    // Grab a listing of all the JavaScript files and check that they're     // passed to the callback.     $all_files = $this->fileSystem->scanDirectory($this->path, '/^javascript-/');
    ksort($all_files);
    $this->assertCount(2, $all_files, 'Found two, expected javascript files.');

    // Check the first file.     $file = reset($all_files);
    $this->assertEquals(key($all_files)$file->uri, 'Correct array key was used for the first returned file.');
    $this->assertEquals($this->path . '/javascript-1.txt', $file->uri, 'First file name was set correctly.');
    $this->assertEquals('javascript-1.txt', $file->filename, 'First basename was set correctly');
    $this->assertEquals('javascript-1', $file->name, 'First name was set correctly.');

    // Check the second file.
$this->logger->warning('Could not prepare thumbnail destination directory @dir for oEmbed media.', [
        '@dir' => $directory,
      ]);
      return NULL;
    }

    // The local filename of the thumbnail is always a hash of its remote URL.     // If a file with that name already exists in the thumbnails directory,     // regardless of its extension, return its URI.     $remote_thumbnail_url = $remote_thumbnail_url->toString();
    $hash = Crypt::hashBase64($remote_thumbnail_url);
    $files = $this->fileSystem->scanDirectory($directory, "/^$hash\..*/");
    if (count($files) > 0) {
      return reset($files)->uri;
    }

    // The local thumbnail doesn't exist yet, so we need to download it.     try {
      $response = $this->httpClient->request('GET', $remote_thumbnail_url);
      if ($response->getStatusCode() === 200) {
        $local_thumbnail_uri = $directory . DIRECTORY_SEPARATOR . $hash . '.' . $this->getThumbnailFileExtensionFromUrl($remote_thumbnail_url$response);
        $this->fileSystem->saveData((string) $response->getBody()$local_thumbnail_uri, FileSystemInterface::EXISTS_REPLACE);
        return $local_thumbnail_uri;
      }
$this->assertFileExists($expected_path . '/' . $image_files[0]->filename);

    // Remove the image.     $this->drupalGet('node/' . $node . '/edit');
    $this->submitForm([], 'Remove');
    $this->submitForm([], 'Save');

    // Get invalid image test files.     $dir = 'core/tests/fixtures/files';
    $files = [];
    if (is_dir($dir)) {
      $files = $file_system->scanDirectory($dir, '/invalid-img-.*/');
    }
    $invalid_image_files = [];
    foreach ($files as $file) {
      $invalid_image_files[$file->filename] = $file;
    }

    // Try uploading a zero-byte image.     $zero_size_image = $invalid_image_files['invalid-img-zero-size.png'];
    $edit = [
      'files[' . $field_name . '_0]' => $file_system->realpath($zero_size_image->uri),
    ];
    
    $this->expectException(MissingGroupException::class);
    TestDiscovery::getTestInfo('Drupal\Tests\ThisTestDoesNotExistTest', '');
  }

  /** * Ensure TestDiscovery::scanDirectory() ignores certain abstract file types. * * @covers ::scanDirectory */
  public function testScanDirectoryNoAbstract() {
    $this->setupVfsWithTestClasses();
    $files = TestDiscovery::scanDirectory('Drupal\\Tests\\test_module\\Kernel\\', vfsStream::url('drupal/modules/test_module/tests/src/Kernel'));
    $this->assertNotEmpty($files);
    $this->assertArrayNotHasKey('Drupal\Tests\test_module\Kernel\KernelExampleTestBase', $files);
    $this->assertArrayNotHasKey('Drupal\Tests\test_module\Kernel\KernelExampleTrait', $files);
    $this->assertArrayNotHasKey('Drupal\Tests\test_module\Kernel\KernelExampleInterface', $files);
    $this->assertArrayHasKey('Drupal\Tests\test_module\Kernel\KernelExampleTest3', $files);
  }

}

  public function deleteAll() {
    $this->state->delete('drupal_css_cache_files');

    $delete_stale = function D$uri) {
      // Default stale file threshold is 30 days.       if (\Drupal::time()->getRequestTime() - filemtime($uri) > \Drupal::config('system.performance')->get('stale_file_threshold')) {
        $this->fileSystem->delete($uri);
      }
    };
    if (is_dir('assets://css')) {
      $this->fileSystem->scanDirectory('assets://css', '/.*/', ['callback' => $delete_stale]);
    }
  }

}
Home | Imprint | This part of the site doesn't use cookies.