Create missing child nodes for the given node type

@param NodeType $nodeType
@param string $workspaceName
@param boolean $dryRun
@return void
@throws NodeTypeNotFoundException
@throws NodeConfigurationException
421546
protected function createChildNodesByNodeType(NodeType $nodeType, $workspaceName, $dryRun)
    {
        $createdNodesCount = 0;
        $updatedNodesCount = 0;
        $incorrectNodeTypeCount = 0;
        $nodeCreationExceptions = 0;

        $nodeIdentifiersWhichNeedUpdate = [];

        $nodeTypes = $this->nodeTypeManager->getSubNodeTypes($nodeType->getName(), false);
        $nodeTypes[$nodeType->getName()] = $nodeType;

        if ($this->nodeTypeManager->hasNodeType((string)$nodeType)) {
            $nodeType = $this->nodeTypeManager->getNodeType((string)$nodeType);
            $nodeTypeNames[$nodeType->getName()] = $nodeType;
        } else {
            $this->dispatch(self::EVENT_ERROR, sprintf('Node type "<i>%s</i>" does not exist', (string)$nodeType));
            return;
        }

        /** @var $nodeType NodeType */
        foreach ($nodeTypes as $nodeTypeName => $nodeType) {
            $childNodes = $nodeType->getAutoCreatedChildNodes();
            if (count($childNodes) === 0) {
                continue;
            }
            foreach ($this->getNodeDataByNodeTypeAndWorkspace($nodeTypeName, $workspaceName) as $nodeData) {
                $context = $this->nodeFactory->createContextMatchingNodeData($nodeData);
                $node = $this->nodeFactory->createFromNodeData($nodeData, $context);
                if (!$node instanceof NodeInterface) {
                    continue;
                }
                foreach ($childNodes as $childNodeName => $childNodeType) {
                    $childNode = $node->getNode($childNodeName);
                    $childNodeIdentifier = Utility::buildAutoCreatedChildNodeIdentifier($childNodeName, $node->getIdentifier());
                    if ($childNode === null) {
                        $taskDescription = sprintf('Add node <i>%s</i> named "<i>%s</i>" in "<i>%s</i>"', $childNodeIdentifier, $childNodeName, $node->getPath());
                        $taskClosure = function () use ($node, $childNodeName, $childNodeType, $childNodeIdentifier, &$nodeCreationExceptions) {
                            try {
                                $node->createNode($childNodeName, $childNodeType, $childNodeIdentifier);
                            } catch (\Exception $exception) {
                                $this->dispatch(self::EVENT_WARNING, sprintf('Could not create node named "<i>%s</i>" in "<i>%s</i>" (<i>%s</i>)', $childNodeName, $node->getPath(), $exception->getMessage()));
                                $nodeCreationExceptions++;
                            }
                        };
                        $this->dispatch(self::EVENT_TASK, $taskDescription, $taskClosure);
                        $createdNodesCount++;
                    } elseif ($childNode->isRemoved() === true) {
                        $taskDescription = sprintf('Undelete node <i>%s</i> named "<i>%s</i>" in "<i>%s</i>"', $childNodeIdentifier, $childNodeName, $node->getPath());
                        $taskClosure = function () use ($node) {
                            $node->setRemoved(false);
                        };
                        $this->dispatch(self::EVENT_TASK, $taskDescription, $taskClosure);
                        $createdNodesCount++;
                    } elseif ($childNode->getIdentifier() !== $childNodeIdentifier) {
                        $nodeIdentifiersWhichNeedUpdate[$childNode->getIdentifier()] = $childNodeIdentifier;
                    } elseif ($childNode->getNodeType() !== $childNodeType) {
                        $taskDescription = sprintf('Set node type of node <i>%s</i>: <i>%s</i> => <i>%s</i>', $childNodeIdentifier, $childNode->getNodeType(), $childNodeType);
                        $taskClosure = function () use ($childNode, $childNodeType) {
                            $childNode->setNodeType($childNodeType);
                        };
                        $this->dispatch(self::EVENT_TASK, $taskDescription, $taskClosure);
                        $incorrectNodeTypeCount++;
                    }
                }
            }
        }
        foreach ($nodeIdentifiersWhichNeedUpdate as $oldNodeIdentifier => $newNodeIdentifier) {
            $taskDescription = sprintf('Update node identifier from <i>%s</i> to <i>%s</i> because it is not a "stable" identifier', $oldNodeIdentifier, $newNodeIdentifier);
            $taskClosure = function () use ($oldNodeIdentifier, $newNodeIdentifier) {
                $queryBuilder = $this->entityManager->createQueryBuilder();
                $queryBuilder->update(NodeData::class, 'n')
                    ->set('n.identifier', $queryBuilder->expr()->literal($newNodeIdentifier))
                    ->where('n.identifier = :oldNodeIdentifier')
                    ->setParameter('oldNodeIdentifier', $oldNodeIdentifier);
                $queryBuilder->getQuery()->getResult();
            };
            $this->dispatch(self::EVENT_TASK, $taskDescription, $taskClosure);
            $updatedNodesCount++;
        }

        if ($createdNodesCount !== 0 || $nodeCreationExceptions !== 0 || $updatedNodesCount !== 0 || $incorrectNodeTypeCount !== 0) {
            if ($dryRun === false) {
                if ($createdNodesCount > 0) {
                    $this->dispatch(self::EVENT_NOTICE, sprintf('Created <i>%d</i> new child nodes', $createdNodesCount));
                }
                if ($updatedNodesCount > 0) {
                    $this->dispatch(self::EVENT_NOTICE, sprintf('Updated identifier of <i>%d</i> child nodes', $updatedNodesCount));
                }
                if ($incorrectNodeTypeCount > 0) {
                    $this->dispatch(self::EVENT_NOTICE, sprintf('Changed node type of <i>%d</i> child nodes', $incorrectNodeTypeCount));
                }
                if ($nodeCreationExceptions > 0) {
                    $this->dispatch(self::EVENT_NOTICE, sprintf('<i>%d</i> Errors occurred during child node creation', $nodeCreationExceptions));
                }
                $this->persistenceManager->persistAll();
            } else {
                if ($createdNodesCount > 0) {
                    $this->dispatch(self::EVENT_NOTICE, sprintf('<i>%d</i> missing child nodes need to be created', $createdNodesCount));
                }
                if ($updatedNodesCount > 0) {
                    $this->dispatch(self::EVENT_NOTICE, sprintf('<i>%d</i> identifiers of child nodes need to be updated', $updatedNodesCount));
                }
                if ($incorrectNodeTypeCount > 0) {
                    $this->dispatch(self::EVENT_NOTICE, sprintf('<i>%d</i> child nodes have incorrect node type', $incorrectNodeTypeCount));
                }
            }
        }
    }
338988
protected function reindex(array $nodes, int &$reindexed, SymfonyStyle $io, array $context, int $batch, bool $dryRun = false, bool $skipErrors = false): void
    {
        if ($dryRun) {
            $io->note(sprintf('DRY RUN - Would reindex node batch %d here.', $batch));
        } else {
            try {
                $this->ncrSearch->indexNodes($nodes, $context);
            } catch (\Throwable $e) {
                $io->error($e->getMessage());
                $io->note(sprintf('Failed to index batch %d.', $batch));
                $io->newLine(2);

                if (!$skipErrors) {
                    throw $e;
                }
            }
        }

        $reindexed += count($nodes);
    }
1104678
public function countByWorkspace(Workspace $workspace)
    {
        $query = $this->createQuery();
        $nodesInDatabase = $query->matching($query->equals('workspace', $workspace))->execute()->count();

        $nodesInMemory = 0;
        /** @var $node NodeData */
        foreach ($this->addedNodes as $node) {
            if ($node->getWorkspace()->getName() === $workspace->getName()) {
                $nodesInMemory++;
            }
        }

        return $nodesInDatabase + $nodesInMemory;
    }
143946
private void blacklist(String nodeName, ResourceType type) {
    List<ResourceType> blacklistedResourceTypes =
      blacklistedNodes.get(nodeName);
    if (blacklistedResourceTypes == null) {
      blacklistedResourceTypes = new ArrayList<ResourceType>();
      blacklistedNodes.put(nodeName, blacklistedResourceTypes);
    }
    synchronized (blacklistedResourceTypes) {
      if (!blacklistedResourceTypes.contains(type)) {
        blacklistedResourceTypes.add(type);
      }
    }
  }
473205
public function export($node, $exportType = 'full')
    {
        if (!$this->isAliasOfMasterCollection() || (($this->c instanceof Page) && $this->c->isMasterCollection())) {
            // We have the OR up here so that master collections that you have duplicated from other
            // master collections export properly.
            $blockNode = $node->addChild('block');
            $blockNode->addAttribute('type', $this->getBlockTypeHandle());
            $blockNode->addAttribute('name', $this->getBlockName());
            if ($this->getBlockFilename() != '') {
                $blockNode->addAttribute('custom-template', $this->getBlockFilename());
            }
            if ($this->overrideBlockTypeContainerSettings()) {
                $blockNode->addAttribute('custom-container-settings', $this->enableBlockContainer() ? 1 : 0);
            }
            if (($this->c instanceof Page) && $this->c->isMasterCollection()) {
                $mcBlockID = Loader::helper('validation/identifier')->getString(8);
                ContentExporter::addMasterCollectionBlockID($this, $mcBlockID);
                $blockNode->addAttribute('mc-block-id', $mcBlockID);
            }

            if ($exportType == 'full') {
                $style = $this->getCustomStyle();
                if (is_object($style)) {
                    $set = $style->getStyleSet();
                    $set->export($blockNode);
                }
                if ($this->overrideBlockTypeCacheSettings()) {
                    $settings = $this->getBlockCacheSettingsObject();
                    $blockNode['cache-output'] = $settings->cacheBlockOutput();
                    $blockNode['cache-output-lifetime'] = $settings->getBlockOutputCacheLifetime();
                    $blockNode['cache-output-on-post'] = $settings->cacheBlockOutputOnPost();
                    $blockNode['cache-output-for-registered-users'] = $settings->cacheBlockOutputForRegisteredUsers();
                }
                $bc = $this->getController();
                $bc->export($blockNode);
            }
        } else {
            $blockNode = $node->addChild('block');
            $blockNode->addAttribute('mc-block-id', ContentExporter::getMasterCollectionTemporaryBlockID($this));
        }
    }
249295
protected function updateWorkspaceInfo(string $documentNodeContextPath)
    {
        $updateWorkspaceInfo = new UpdateWorkspaceInfo();
        $documentNode = $this->nodeService->getNodeFromContextPath($documentNodeContextPath, null, null, true);
        $updateWorkspaceInfo->setWorkspace(
            $documentNode->getContext()->getWorkspace()
        );

        $this->feedbackCollection->add($updateWorkspaceInfo);
    }
831004
public function createChildNodes(NodeInterface $node)
    {
        $nodeType = $node->getNodeType();
        foreach ($nodeType->getAutoCreatedChildNodes() as $childNodeName => $childNodeType) {
            try {
                $node->createNode($childNodeName, $childNodeType);
            } catch (NodeExistsException $exception) {
                // If you have a node that has been marked as removed, but is needed again
                // the old node is recovered
                $childNodePath = NodePaths::addNodePathSegment($node->getPath(), $childNodeName);
                $contextProperties = $node->getContext()->getProperties();
                $contextProperties['removedContentShown'] = true;
                $context = $this->contextFactory->create($contextProperties);
                $childNode = $context->getNode($childNodePath);
                if ($childNode->isRemoved()) {
                    $childNode->setRemoved(false);
                }
            }
        }
    }
1317758
public function moveToNextByNodeType($nodeType)
    {
        if (null === self::valid()) {
            self::rewind();
        } elseif (self::valid()) {
            self::next();
        }

        while (self::valid()) {
            if ($this->reader->nodeType === $nodeType) {
                break;
            }
            self::next();
        }

        return self::valid() ? self::current() : false;
    }
1232480
public function showCommand(string $nodeType = null): void
    {
        if ($nodeType !== null) {
            /** @var NodeType $nodeType */
            $nodeType = $this->nodeTypeManager->getNodeType($nodeType);
            $configuration = $nodeType->getFullConfiguration();
        } else {
            $nodeTypes = $this->nodeTypeManager->getNodeTypes();
            $configuration = [];
            /** @var NodeType $nodeType */
            foreach ($nodeTypes as $nodeTypeName => $nodeType) {
                $configuration[$nodeTypeName] = $nodeType->getFullConfiguration();
            }
        }
        $this->output(Yaml::dump($configuration, 5, 2));
    }
692434
public void setNodeType(NodeType type) {
        addField(ConfigureNodeFields.node_type, FormField.Type.list_single);
        setAnswer(ConfigureNodeFields.node_type.getFieldName(), getListSingle(type.toString()));
    }
778090
private void initWorkspace(WorkspaceEntry wsConfig) throws RepositoryException
   {

      WorkspaceContainer workspaceContainer = getWorkspaceContainer(wsConfig.getName());

      // touch independent components
      workspaceContainer.getComponentInstanceOfType(IdGenerator.class);

      // Init Root and jcr:system if workspace is system workspace
      WorkspaceInitializer wsInitializer =
         (WorkspaceInitializer)workspaceContainer.getComponentInstanceOfType(WorkspaceInitializer.class);
      RepositoryCreationSynchronizer synchronizer =
         (RepositoryCreationSynchronizer)getComponentInstanceOfType(RepositoryCreationSynchronizer.class);
      // The synchronizer will be used to synchronize all the cluster
      // nodes to prevent any concurrent jcr initialization i.e. EXOJCR-887
      synchronizer.waitForApproval(wsInitializer.isWorkspaceInitialized());

      SystemParametersPersistenceConfigurator sppc =
         (SystemParametersPersistenceConfigurator)parent
            .getComponentInstanceOfType(SystemParametersPersistenceConfigurator.class);

      if (sppc != null)
      {
         setInitializerAndValidateOverriddenParameters(wsConfig, wsInitializer);
      }

      wsInitializer.initWorkspace();
   }
874028
protected function publishNodeCanBeSkipped(NodeInterface $node, Workspace $targetWorkspace)
    {
        if ($this->baseWorkspace === null) {
            return true;
        }
        if ($node->getWorkspace() !== $this) {
            return true;
        }
        // Might happen if a node which has been published during an earlier call of publishNode() is attempted to
        // be published again:
        if ($node->getWorkspace() === $targetWorkspace) {
            return true;
        }
        $this->verifyPublishingTargetWorkspace($targetWorkspace);
        if ($node->getPath() === '/') {
            return true;
        }

        return false;
    }
609809
public function create(
        $contentTypes,
        $limit,
        $titleWords,
        $timeRange,
        $language = LanguageInterface::LANGCODE_NOT_SPECIFIED
    ) {
        $nodes = [];
        $bundles = $this->drupalApi->getBundles();
        for ($i = 0; $i < $limit; $i++) {
            try {
                $contentType = $contentTypes[array_rand($contentTypes)];
                $node = $this->entityTypeManager->getStorage('node')->create(
                    [
                        'nid' => null,
                        'type' => $contentType,
                        'created' => REQUEST_TIME - mt_rand(0, $timeRange),
                        'uid' => $this->getUserID(),
                        'title' => $this->getRandom()->sentences(mt_rand(1, $titleWords), true),
                        'revision' => mt_rand(0, 1),
                        'status' => true,
                        'promote' => mt_rand(0, 1),
                        'langcode' => $language
                    ]
                );

                $this->generateFieldSampleData($node);
                $node->save();
                $nodes['success'][] = [
                    'nid' => $node->id(),
                    'node_type' => $bundles[$contentType],
                    'title' => $node->getTitle(),
                    'created' => $this->dateFormatter->format(
                        $node->getCreatedTime(),
                        'custom',
                        'Y-m-d h:i:s'
                    )
                ];
            } catch (\Exception $error) {
                $nodes['error'][] = $error->getMessage();
            }
        }

        return $nodes;
    }
823355
protected function getNodeDataByNodeTypeAndWorkspace($nodeType, $workspaceName)
    {
        /** @var QueryBuilder $queryBuilder */
        $queryBuilder = $this->entityManager->createQueryBuilder();

        $queryBuilder->select('n')
            ->distinct()
            ->from(NodeData::class, 'n')
            ->where('n.nodeType = :nodeType')
            ->andWhere('n.workspace = :workspace')
            ->andWhere('n.movedTo IS NULL OR n.removed = :removed')
            ->setParameter('nodeType', $nodeType)
            ->setParameter('workspace', $workspaceName)
            ->setParameter('removed', false, \PDO::PARAM_BOOL);
        return $queryBuilder->getQuery()->getResult();
    }
10066
public function isNodeTypeAllowedAsChildNode(NodeType $nodeType): bool
    {
        if ($this->isAutoCreated()) {
            return $this->getParent()->getNodeType()->allowsGrandchildNodeType($this->getName(), $nodeType);
        } else {
            return $this->getNodeType()->allowsChildNodeType($nodeType);
        }
    }
551635
public function setNodeType($nodeType)
    {
        if (is_string($nodeType)) {
            $nodeType = $this->nodeTypeManager->getNodeType($nodeType);
        }

        if (!$nodeType instanceof NodeType) {
            throw new \InvalidArgumentException('nodeType needs to be of type string or NodeType', 1452100970);
        }

        $this->nodeType = $nodeType;
    }
935873
public function nodeExistsInWorkspace(NodeInterface $node, Workspace $workspace)
    {
        $context = ['workspaceName' => $workspace->getName()];
        $flowQuery = new FlowQuery([$node]);

        return $flowQuery->context($context)->count() > 0;
    }