Recursive doctrine document processing

@param Document $document      Document
@param string   $exposedPrefix Exposed field prefix
@return array
965981
private function processDocument(Document $document, $exposedPrefix = '')
    {
        $result = [];
        foreach ($document->getFields() as $field) {
            if ($field instanceof Field) {
                if ($field->getType() === 'extref') {
                    $result[] = $exposedPrefix.$field->getExposedName();
                }
            } elseif ($field instanceof ArrayField) {
                if ($field->getItemType() === 'extref') {
                    $result[] = $exposedPrefix.$field->getExposedName().'.0';
                }
            } elseif ($field instanceof EmbedOne) {
                $result = array_merge(
                    $result,
                    $this->processDocument(
                        $field->getDocument(),
                        $exposedPrefix.$field->getExposedName().'.'
                    )
                );
            } elseif ($field instanceof EmbedMany) {
                $result = array_merge(
                    $result,
                    $this->processDocument(
                        $field->getDocument(),
                        $exposedPrefix.$field->getExposedName().'.0.'
                    )
                );
            }
        }

        return $result;
    }
1074798
protected function getDocumentData($document)
    {
        if (is_array($document)) {
            $data = $document;
        } elseif ($document instanceof AbstractDocument) {
            $reflectionClass = new \ReflectionClass($document);
            $documentProperty = $reflectionClass->getParentClass()->getProperty('document');
            $documentProperty->setAccessible(true);
            $data = $documentProperty->getValue($document);
            foreach ($data as $key => &$value) {
                if ($value instanceof DocumentSerializableInterface) {
                    $value = $value->documentSerialize()->jsonSerialize();
                }
            }
        } else {
            throw new \Exception('Invalid data type, array or AbstractDocument expected');
        }

        return $data;
    }
1345693
public function getProbabilities($document)
    {
        if ($this->hasThreshold()) {
            $model = $this->preparedModel();
            $data = $this->prepareDocument($document, $model);
            $probabilities = array();
            $model->getModel()->predict_probability($data, $probabilities);

            return array_combine($model->getCategoryMap(), $probabilities);
        }
    }
1056337
public function ensureDocumentIndexes($documentName, $timeout = null)
    {
        $class = $this->dm->getClassMetadata($documentName);
        if ($class->isMappedSuperclass || $class->isEmbeddedDocument) {
            throw new \InvalidArgumentException('Cannot create document indexes for mapped super classes or embedded documents.');
        }
        if ($indexes = $this->getDocumentIndexes($documentName)) {
            $collection = $this->dm->getDocumentCollection($class->name);
            foreach ($indexes as $index) {
                $keys = $index['keys'];
                $options = $index['options'];

                if ( ! isset($options['safe']) && ! isset($options['w'])) {
                    if (version_compare(phpversion('mongo'), '1.3.0', '<')) {
                        $options['safe'] = true;
                    } else {
                        $options['w'] = 1;
                    }
                }

                if (isset($options['safe']) && ! isset($options['w']) &&
                    version_compare(phpversion('mongo'), '1.3.0', '>=')) {

                    $options['w'] = is_bool($options['safe']) ? (integer) $options['safe'] : $options['safe'];
                    unset($options['safe']);
                }

                if ( ! isset($options['timeout']) && isset($timeout)) {
                    $options['timeout'] = $timeout;
                }

                $collection->ensureIndex($keys, $options);
            }
        }
    }
1201344
protected function addDocumentsWhenLimitNotReached(array $documents, SearchResultCollection $documentsToAdd, int $maxDocuments)  : array
    {
        $additionalTopResultsFields = $this->typoScriptConfiguration->getSuggestAdditionalTopResultsFields();
        /** @var SearchResult $document */
        foreach ($documentsToAdd as $document) {
            $documents[] = $this->getDocumentAsArray($document, $additionalTopResultsFields);
            if (count($documents) >= $maxDocuments) {
                return $documents;
            }
        }

        return $documents;
    }
50141
public static function getAll( $prefix = NULL, $excludePrefix = NULL )
	{
		$prefix	= strtoupper( $prefix );
		$length	= strlen( $prefix );
		if( $length	< 2 )
			throw new InvalidArgumentException( 'Prefix "'.$prefix.'" is to short.' );
		$map	= get_defined_constants();
		if( $prefix ){
			foreach( $map as $key => $value )
			{
				if( $key[0] !== $prefix[0] )
					unset( $map[$key] );
				else if( $key[1] !== $prefix[1] )
					unset( $map[$key] );
				else if( substr( $key, 0, $length ) !== $prefix )
					unset( $map[$key] );
#				remark( $prefix." - ".$key." - ".(int)isset( $map[$key] ) );
			}
		}
		if( $excludePrefix ){
			if( substr( $excludePrefix, 0, $length ) !== $prefix )
				$excludePrefix	= $prefix.$excludePrefix;
			foreach( $map as $key => $value ){
				if( substr( $key, 0, strlen( $excludePrefix ) ) === $excludePrefix )
					unset( $map[$key] );
			}
		}
		return $map;
	}
438330
private function cascadeRefresh($document, array &$visited)
    {
        $class = $this->dm->getClassMetadata(get_class($document));

        $associationMetadata = array_filter(
            $class->associationMetadata,
            function ($assoc) {
                return $assoc->isCascadeRefresh;
            }
        );

        foreach ($associationMetadata as $mapping) {
            $relatedDocuments = $class->getPropertyMetadata($mapping->name)->getValue($document);
            if ($relatedDocuments instanceof Collection || is_array($relatedDocuments)) {
                if ($relatedDocuments instanceof PersistentCollectionInterface) {
                    // Unwrap so that foreach() does not initialize
                    $relatedDocuments = $relatedDocuments->unwrap();
                }
                foreach ($relatedDocuments as $relatedDocument) {
                    $this->doRefresh($relatedDocument, $visited);
                }
            } elseif ($relatedDocuments !== null) {
                $this->doRefresh($relatedDocuments, $visited);
            }
        }
    }
305449
private function cascadePersist(object $document, array &$visited) : void
    {
        $class = $this->dm->getClassMetadata(get_class($document));

        $associationMappings = array_filter(
            $class->associationMappings,
            static function ($assoc) {
                return $assoc['isCascadePersist'];
            }
        );

        foreach ($associationMappings as $fieldName => $mapping) {
            $relatedDocuments = $class->reflFields[$fieldName]->getValue($document);

            if ($relatedDocuments instanceof Collection || is_array($relatedDocuments)) {
                if ($relatedDocuments instanceof PersistentCollectionInterface) {
                    if ($relatedDocuments->getOwner() !== $document) {
                        $relatedDocuments = $this->fixPersistentCollectionOwnership($relatedDocuments, $document, $class, $mapping['fieldName']);
                    }
                    // Unwrap so that foreach() does not initialize
                    $relatedDocuments = $relatedDocuments->unwrap();
                }

                $count = 0;
                foreach ($relatedDocuments as $relatedKey => $relatedDocument) {
                    if (! empty($mapping['embedded'])) {
                        [, $knownParent ] = $this->getParentAssociation($relatedDocument);
                        if ($knownParent && $knownParent !== $document) {
                            $relatedDocument               = clone $relatedDocument;
                            $relatedDocuments[$relatedKey] = $relatedDocument;
                        }
                        $pathKey = CollectionHelper::isList($mapping['strategy']) ? $count++ : $relatedKey;
                        $this->setParentAssociation($relatedDocument, $mapping, $document, $mapping['fieldName'] . '.' . $pathKey);
                    }
                    $this->doPersist($relatedDocument, $visited);
                }
            } elseif ($relatedDocuments !== null) {
                if (! empty($mapping['embedded'])) {
                    [, $knownParent ] = $this->getParentAssociation($relatedDocuments);
                    if ($knownParent && $knownParent !== $document) {
                        $relatedDocuments = clone $relatedDocuments;
                        $class->setFieldValue($document, $mapping['fieldName'], $relatedDocuments);
                    }
                    $this->setParentAssociation($relatedDocuments, $mapping, $document, $mapping['fieldName']);
                }
                $this->doPersist($relatedDocuments, $visited);
            }
        }
    }
986805
public function convert(DOMDocument $document)
    {
        foreach ($this->converters as $converter) {
            $converter->convert($document);
        }

        return $document;
    }
1098548
public function getFieldValue($document, $field)
    {
        if (isset($this->reflFields[$field])) {
            return $this->reflFields[$field]->getValue($document);
        }
    }
1204213
public function getOriginalDocumentData($document)
    {
        $oid = spl_object_hash($document);
        if (isset($this->originalDocumentData[$oid])) {
            return $this->originalDocumentData[$oid];
        }
        return array();
    }
1139697
private function mapCollectionField($document, Field $field, $sourceTargetObject)
    {
        /** @var Collection $collection */
        $collection = $field->getValue();
        $getter = $field->getGetterName();

        if ($getter != '') {
            $collection = $this->callGetterMethod($sourceTargetObject, $getter);

            $collection = array_filter($collection, function ($value) {
                return $value !== null;
            });
        }

        $values = [];
        if (count($collection)) {
            foreach ($collection as $relatedObj) {
                if (is_object($relatedObj)) {
                    $values[] = $this->objectToDocument($relatedObj);
                } else {
                    $values[] = $relatedObj;
                }
            }

            $document->addField('_childDocuments_', $values, $field->getBoost());
        }

        return $values;
    }
826414
public function convert(DOMDocument $document)
    {
        $xpath = new DOMXPath($document);
        $xpath->registerNamespace('docbook', 'http://docbook.org/ns/docbook');
        $xpathExpression = '//docbook:eztemplate | //docbook:eztemplateinline';

        $templates = $xpath->query($xpathExpression);
        /** @var \DOMElement[] $templatesSorted */
        $templatesSorted = array();
        $maxDepth = 0;

        foreach ($templates as $template) {
            $depth = $this->getNodeDepth($template);
            if ($depth > $maxDepth) {
                $maxDepth = $depth;
            }
            $templatesSorted[$depth][] = $template;
        }

        ksort($templatesSorted, SORT_NUMERIC);

        foreach ($templatesSorted as $templates) {
            foreach ($templates as $template) {
                $this->processTemplate($document, $template);
            }
        }

        return $document;
    }
859110
private function relationsFromExpand(array $relations, array $expandPrefixes)
    {
        $valid = [];
        foreach ($expandPrefixes as $prefix) {
            foreach ($relations as $relation) {
                if (StringHelper::startsWith($relation, $prefix)) {
                    $valid[] = $relation;
                }
            }
        }
        return $valid;
    }
585827
public function process(\DOMDocument $xml)
    {
        $xpath = new \DOMXPath($xml);
        $nodes = $xpath->query(
            '/project/file/class/docblock/tag[@name="property"]'
            . '|/project/file/class/docblock/tag[@name="property-read"]'
            . '|/project/file/class/docblock/tag[@name="property-write"]'
        );

        /** @var \DOMElement $node */
        foreach ($nodes as $node) {
            $class = $node->parentNode->parentNode;

            $property = new \DOMElement('property');
            $class->appendChild($property);

            $property->setAttribute('final', 'false');
            $property->setAttribute('static', 'false');
            $property->setAttribute('visibility', 'public');
            $property->setAttribute('line', $node->getAttribute('line'));
            $property->appendChild(
                new \DOMElement('name', $node->getAttribute('variable'))
            );
            $property->appendChild(new \DOMElement('default'));

            $docblock = new \DOMElement('docblock');
            $property->appendChild($docblock);
            $docblock->appendChild(
                new \DOMElement('description', $node->getAttribute('description'))
            );
            $docblock->appendChild(new \DOMElement('long-description'));

            $var_tag = new \DOMElement('tag');
            $docblock->appendChild($var_tag);
            $var_tag->setAttribute('name', 'var');
            $var_tag->setAttribute('description', $node->getAttribute('description'));
            $var_tag->setAttribute('type', $node->getAttribute('type'));
            $var_tag->setAttribute('line', $node->getAttribute('line'));

            $var_tag_type = new \DOMElement('type', $node->getAttribute('type'));
            $var_tag->appendChild($var_tag_type);
            $var_tag_type->setAttribute('by_reference', 'false');

            $magic_tag = new \DOMElement('tag');
            $docblock->appendChild($magic_tag);
            $magic_tag->setAttribute('name', 'magic');
            $magic_tag->setAttribute('line', $node->getAttribute('line'));

            $node->parentNode->removeChild($node);
            $docblock->appendChild($node);
        }

        return $xml;
    }
111695
private function _filterFields($aFields, $sPrefix)
    {
        $aAllowed = [];
        foreach ($aFields as $sKey => $sValue) {
            if (strpos($sValue, $sPrefix) === 0) {
                $aAllowed[] = $aFields[$sKey];
            }
        }

        return $aAllowed;
    }
1342885
private function addIdPrefix($fields, $idPrefix)
    {
        $result = array();
        foreach ($fields as $key => $field) {
            $newKey = $idPrefix . $key;
            $result[$newKey] = $field;
            if (isset($field['fields'])) {
                $result[$newKey]['fields'] = $this->addIdPrefix($field['fields'], $newKey . '_');
            }
        }
        return $result;
    }