Checks if a nodetranslation has children and update their url

@param NodeTranslation        $node  The node
@param EntityManagerInterface $em    The entity manager
@param ClassMetadata          $class The class meta daat
504993
private function updateNodeChildren(NodeTranslation $node, EntityManagerInterface $em, ClassMetadata $class)
    {
        $children = $node->getNode()->getChildren();
        if (\count($children) > 0) {
            /* @var Node $child */
            foreach ($children as $child) {
                $translation = $child->getNodeTranslation($node->getLang(), true);
                if ($translation) {
                    $translation = $this->updateUrl($translation, $em);

                    if ($translation !== false) {
                        $em->persist($translation);
                        $em->getUnitOfWork()->recomputeSingleEntityChangeSet($class, $translation);

                        $this->updateNodeChildren($translation, $em, $class);
                    }
                }
            }
        }
    }
552701
public function enterNode(Node $node)
    {
        if ($node instanceof Class_) {
            if ($node->extends) {
                $extends = (string) $node->extends;
                if ($this->isFinalClass($extends)) {
                    $msg = \sprintf('Class %s may not inherit from final class (%s)', $node->name, $extends);
                    throw new FatalErrorException($msg, 0, E_ERROR, null, $node->getLine());
                }
            }

            if ($node->isFinal()) {
                $this->finalClasses[\strtolower($node->name)] = true;
            }
        }
    }
792982
public function prefetchReferences(ClassMetadata $class, NodeInterface $node)
    {
        $prefetch = $this->collectPrefetchReferences($class, $node);
        if (count($prefetch)) {
            $node->getSession()->getNodesByIdentifier($prefetch);
        }
    }
1121215
public function execute(NodeData $node)
    {
        foreach ($node->getNodeType()->getProperties() as $propertyName => $propertyConfiguration) {
            if (isset($propertyConfiguration['type']) && ($propertyConfiguration['type'] === ImageInterface::class || preg_match('/array\<.*\>/', $propertyConfiguration['type']))) {
                if (!isset($nodeProperties)) {
                    $nodeRecordQuery = $this->entityManager->getConnection()->prepare('SELECT properties FROM typo3_typo3cr_domain_model_nodedata WHERE persistence_object_identifier=?');
                    $nodeRecordQuery->execute([$this->persistenceManager->getIdentifierByObject($node)]);
                    $nodeRecord = $nodeRecordQuery->fetch(\PDO::FETCH_ASSOC);
                    $nodeProperties = unserialize($nodeRecord['properties']);
                }

                if (!isset($nodeProperties[$propertyName]) || empty($nodeProperties[$propertyName])) {
                    continue;
                }

                if ($propertyConfiguration['type'] === ImageInterface::class) {
                    $adjustments = [];
                    $oldVariantConfiguration = $nodeProperties[$propertyName];
                    if (is_array($oldVariantConfiguration)) {
                        foreach ($oldVariantConfiguration as $variantPropertyName => $property) {
                            switch (substr($variantPropertyName, 3)) {
                                case 'originalImage':
                                    /**
                                     * @var $originalAsset \Neos\Media\Domain\Model\Image
                                     */
                                    $originalAsset = $this->assetRepository->findByIdentifier($this->persistenceManager->getIdentifierByObject($property));
                                    break;
                                case 'processingInstructions':
                                    $adjustments = $this->processingInstructionsConverter->convertFrom($property, 'array');
                                    break;
                            }
                        }

                        $nodeProperties[$propertyName] = null;
                        if (isset($originalAsset)) {
                            $stream = $originalAsset->getResource()->getStream();
                            if ($stream === false) {
                                continue;
                            }

                            fclose($stream);
                            $newImageVariant = new ImageVariant($originalAsset);
                            foreach ($adjustments as $adjustment) {
                                $newImageVariant->addAdjustment($adjustment);
                            }
                            $originalAsset->addVariant($newImageVariant);
                            $this->assetRepository->update($originalAsset);
                            $nodeProperties[$propertyName] = $this->persistenceManager->getIdentifierByObject($newImageVariant);
                        }
                    }
                } elseif (preg_match('/array\<.*\>/', $propertyConfiguration['type'])) {
                    if (is_array($nodeProperties[$propertyName])) {
                        $convertedValue = [];
                        foreach ($nodeProperties[$propertyName] as $entryValue) {
                            if (!is_object($entryValue)) {
                                continue;
                            }

                            $stream = $entryValue->getResource()->getStream();
                            if ($stream === false) {
                                continue;
                            }

                            fclose($stream);
                            $existingObjectIdentifier = null;
                            try {
                                $existingObjectIdentifier = $this->persistenceManager->getIdentifierByObject($entryValue);
                                if ($existingObjectIdentifier !== null) {
                                    $convertedValue[] = $existingObjectIdentifier;
                                }
                            } catch (\Exception $exception) {
                            }
                        }
                        $nodeProperties[$propertyName] = $convertedValue;
                    }
                }
            }
        }

        if (isset($nodeProperties)) {
            $nodeUpdateQuery = $this->entityManager->getConnection()->prepare('UPDATE typo3_typo3cr_domain_model_nodedata SET properties=? WHERE persistence_object_identifier=?');
            $nodeUpdateQuery->execute([serialize($nodeProperties), $this->persistenceManager->getIdentifierByObject($node)]);
        }
    }
535509
public function invoke($node, NodeInterface $parent): void
    {
        if (! $node instanceof Node\Stmt\Class_ || ! $parent instanceof PhpFileModelInterface) {
            throw new Exception('ClassNodeParser is made to parse a class node');
        }
        $class = new ClassModel();
        $class->setParentNode($parent);
        $class->setName(ClassLikeNameHelper::getName($node));
        $class->setIsAbstract($node->isAbstract());
        $class->setIsFinal($node->isFinal());
        $parent->addConcreteUse($parent->getFullNameFor($class->getName()), $class->getName());

        if (($documentation = $node->getDocComment()) !== null) {
            $this->documentationNodeParser->invoke($documentation, $class);
        }

        $this->parseSubNodes($node->stmts, $class);

        $parent->addClass($class);
    }
1207740
public function buildEntityIdMetadata(\SimpleXMLElement $node, $className, \ReflectionClass $reflection)
    {
        if (!isset($node->id) || !isset($node->id['name'])) {
            throw new MappingException(
                sprintf('Class "%s" OGM XML configuration has invalid or missing "id" element', $className)
            );
        }

        return new EntityIdMetadata(
            (string) $node->id['name'],
            $reflection->getProperty((string) $node->id['name']),
            new IdAnnotationMetadata()
        );
    }
226129
private function buildRelationshipMetadata(\SimpleXMLElement $node, $className)
    {
        if (!isset($node['type'])) {
            throw new MappingException(
                sprintf('Class "%s" OGM XML configuration is missing "type" attribute', $className)
            );
        }
        $entity = new RelationshipEntity();
        $entity->type = (string) $node['type'];

        if (isset($node['direction'])) {
            $entity->direction = (string) $node['direction'];
        }

        return $entity;
    }
719794
private function upgradeNode(NodeInterface $node)
    {
        foreach ($node->getProperties('i18n:-*') as $property) {
            $property->remove();
        }

        foreach ($node->getNodes() as $childNode) {
            $this->upgradeNode($childNode);
        }
    }
1222056
protected function addPageToIndex(
        NodeTranslation $nodeTranslation,
        Node $node,
        NodeVersion $publicNodeVersion,
        HasNodeInterface $page
    ) {
        $rootNode = $this->currentTopNode;
        if (!$rootNode) {
            // Fetch main parent of current node...
            $rootNode = $this->em->getRepository('KunstmaanNodeBundle:Node')->getRootNodeFor(
                $node,
                $nodeTranslation->getLang()
            );
        }

        $doc = array(
            'root_id' => $rootNode->getId(),
            'node_id' => $node->getId(),
            'node_translation_id' => $nodeTranslation->getId(),
            'node_version_id' => $publicNodeVersion->getId(),
            'title' => $nodeTranslation->getTitle(),
            'slug' => $nodeTranslation->getFullSlug(),
            'page_class' => ClassLookup::getClass($page),
            'created' => $this->getUTCDateTime(
                $nodeTranslation->getCreated()
            )->format(\DateTime::ISO8601),
            'updated' => $this->getUTCDateTime(
                $nodeTranslation->getUpdated()
            )->format(\DateTime::ISO8601),
        );
        if ($this->logger) {
            $this->logger->info('Indexing document : ' . implode(', ', $doc));
        }

        // Permissions
        $this->addPermissions($node, $doc);

        // Search type
        $this->addSearchType($page, $doc);

        // Parent and Ancestors
        $this->addParentAndAncestors($node, $doc);

        // Content
        $this->addPageContent($nodeTranslation, $page, $doc);

        // Add document to index
        $uid = 'nodetranslation_' . $nodeTranslation->getId();

        $this->addCustomData($page, $doc);

        $this->documents[] = $this->searchProvider->createDocument(
            $uid,
            $doc,
            $this->indexName . '_' . $nodeTranslation->getLang(),
            $this->indexType
        );
    }
275207
private function upgradeNode(NodeInterface $node, $propertyName, $locale)
    {
        foreach ($node->getNodes() as $child) {
            $this->upgradeNode($child, $propertyName, $locale);
        }

        if (false === $node->getPropertyValueWithDefault($propertyName, false)) {
            return;
        }

        $shadowLocale = $node->getPropertyValue($this->getPropertyName(self::SHADOW_BASE_PROPERTY, $locale));

        $tags = $this->getTags($node, $shadowLocale);
        $categories = $this->getCategories($node, $shadowLocale);
        $navigationContext = $this->getNavigationContext($node, $shadowLocale);

        $node->setProperty(sprintf(self::TAGS_PROPERTY, $locale), $tags);
        $node->setProperty(sprintf(self::CATEGORIES_PROPERTY, $locale), $categories);
        $node->setProperty(sprintf(self::NAVIGATION_CONTEXT_PROPERTY, $locale), $navigationContext);
    }
970379
public function translate($entity, $locale)
    {
        $metadata = $this->metadataCollection->getMetadata($entity);
        if($metadata === null) {
            return null;
        }

        //translation data is stored inside the object
        if($locale === $this->defaultLocale) {
            return;
        }

        $accessor = PropertyAccess::createPropertyAccessor();   
        if($metadata !== null) {
            foreach($metadata->getProperties() as $property) {
                $strategy = $this->strategyResolver->getStrategy($property->getStrategy());
                $value = $strategy->getTranslation($entity, $property, $locale, $metadata);
                $accessor->setValue($entity, $property->getName(), $value);
            }
        }
    }
623981
private function hasField(EntityManager $em, $fieldName)
    {
        return (Boolean) $em->createNativeQuery(
            "SHOW FIELDS FROM usr WHERE Field = :field",
            (new ResultSetMapping())->addScalarResult('Field', 'Field')
        )->setParameter(':field', $fieldName)->getOneOrNullResult();
    }
405051
public function onFlush(OnFlushEventArgs $args)
    {
        try {
            $em = $args->getEntityManager();

            $class = $em->getClassMetadata(NodeTranslation::class);

            // Collect all nodetranslations that are updated
            foreach ($em->getUnitOfWork()->getScheduledEntityUpdates() as $entity) {
                if ($entity instanceof NodeTranslation) {
                    /** @var Node $publicNode */
                    $publicNode = $entity->getPublicNodeVersion()->getRef($em);

                    // Do nothing for StructureNode objects, skip.
                    if ($publicNode instanceof HasNodeInterface && $publicNode->isStructureNode()) {
                        continue;
                    }

                    $entity = $this->updateUrl($entity, $em);

                    if ($entity !== false) {
                        $em->persist($entity);
                        $em->getUnitOfWork()->recomputeSingleEntityChangeSet($class, $entity);

                        $this->updateNodeChildren($entity, $em, $class);
                    }
                }
            }
        } catch (MappingException $e) {
            // Different entity manager without this entity configured in namespace chain. Ignore
        }
    }
75656
public function enterNode(Node $node)
    {
        if ($node instanceof Class_) {
            $this->class = $node;
            $this->abstractMethods = [];
        } elseif ($node instanceof ClassMethod) {
            if ($node->isAbstract()) {
                $name = \sprintf('%s::%s', $this->class->name, $node->name);
                $this->abstractMethods[] = $name;

                if ($node->stmts !== null) {
                    $msg = \sprintf('Abstract function %s cannot contain body', $name);
                    throw new FatalErrorException($msg, 0, E_ERROR, null, $node->getLine());
                }
            }
        }
    }
1308622
public function invoke($node, NodeInterface $parent): void
    {
        if (! $node instanceof Node\Stmt\ClassMethod || ! $parent instanceof InterfaceModelInterface) {
            throw new Exception('MethodNodeParser is made to parse a method node');
        }

        // Retrieve visibility
        $function = new FunctionModel();
        $function->setVisibility(MethodVisibilityHelper::getVisibility($node));

        // If no private / protected methods parsing is required
        if (! $function->isPublic() && ! $this->config->hasPrivateParsing()) {
            return;
        }

        $function->setParentNode($parent);
        $function->setName($node->name);
        $function->setIsFinal($node->isFinal());
        $function->setIsStatic($node->isStatic());
        $function->setIsAbstract($node->isAbstract());

        $this->parseFunction($node, $function);

        $parent->addFunction($function);

        if ($this->autoGetterOrSetter($function, $parent)) {
            return;
        }
        if (($documentation = $node->getDocComment()) !== null) {
            $this->documentationNodeParser->invoke($documentation, $function);
        }
    }
469994
private function mapTranslatable(ClassMetadata $metadata)
    {
        // In the case A -> B -> TranslatableInterface, B might not have mapping defined
        // as it is probably defined in A, so in that case, we just return.
        if (!isset($this->configs[$metadata->name])) {
            return;
        }

        $metadata->mapOneToMany([
            'fieldName'     => 'translations',
            'targetEntity'  => $this->configs[$metadata->name],
            'mappedBy'      => 'translatable',
            //'fetch'         => ClassMetadataInfo::FETCH_EXTRA_LAZY,
            'indexBy'       => 'locale',
            'cascade'       => ['persist', 'merge', 'refresh', 'remove', 'detach'],
            'orphanRemoval' => true,
        ]);

        $metadata->addEntityListener('preFlush', self::class, 'onTranslatablePreFlush');
    }
156026
private static boolean doesElementContainTranslatableContentV2(final Node node) {
        final NodeList children = node.getChildNodes();
        if (children != null) {
            // check to see if any of the children are translatable nodes
            for (int j = 0; j < children.getLength(); ++j) {
                final Node child = children.item(j);
                final String childName = child.getNodeName();

                if (TRANSLATABLE_ELEMENTS_OLD.contains(childName)) {
                    // This child node is itself translatable, so return true
                    return true;
                } else if (doesElementContainTranslatableContentV2(child)) {
                    // check if this child contains translatable nodes
                    return true;
                }
            }
        }

        return false;
    }