function Finder::__construct

Same name in other branches
  1. 10 core/lib/Drupal/Core/DefaultContent/Finder.php \Drupal\Core\DefaultContent\Finder::__construct()

File

core/lib/Drupal/Core/DefaultContent/Finder.php, line 28

Class

Finder
Finds all default content in a directory, in dependency order.

Namespace

Drupal\Core\DefaultContent

Code

public function __construct(string $path) {
    try {
        // Scan for all YAML files in the content directory.
        $finder = SymfonyFinder::create()->in($path)
            ->files()
            ->name('*.yml');
    } catch (DirectoryNotFoundException) {
        $this->data = [];
        return;
    }
    $graph = $files = [];
    
    /** @var \Symfony\Component\Finder\SplFileInfo $file */
    foreach ($finder as $file) {
        
        /** @var array{_meta: array{uuid: string|null, depends: array<string, string>|null}} $decoded */
        $decoded = Yaml::decode($file->getContents());
        $decoded['_meta']['path'] = $file->getPathname();
        $uuid = $decoded['_meta']['uuid'] ?? throw new ImportException($decoded['_meta']['path'] . ' does not have a UUID.');
        $files[$uuid] = $decoded;
        // For the graph to work correctly, every entity must be mentioned in it.
        // This is inspired by
        // \Drupal\Core\Config\Entity\ConfigDependencyManager::getGraph().
        $graph += [
            $uuid => [
                'edges' => [],
                'uuid' => $uuid,
            ],
        ];
        foreach ($decoded['_meta']['depends'] ?? [] as $dependency_uuid => $entity_type) {
            $graph[$dependency_uuid]['edges'][$uuid] = TRUE;
            $graph[$dependency_uuid]['uuid'] = $dependency_uuid;
        }
    }
    ksort($graph);
    // Sort the dependency graph. The entities that are dependencies of other
    // entities should come first.
    $graph_object = new Graph($graph);
    $sorted = $graph_object->searchAndSort();
    uasort($sorted, SortArray::sortByWeightElement(...));
    $entities = [];
    foreach ($sorted as [
        'uuid' => $uuid,
    ]) {
        if (array_key_exists($uuid, $files)) {
            $entities[$uuid] = $files[$uuid];
        }
    }
    $this->data = $entities;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.