Create search dcument instance from a ES hit.

@param array $rawDocument ES raw hit.

@return Document
193073
public function create($rawDocument)
    {
        /** @var \Magento\Framework\Search\DocumentField[] $fields */

        $entityIdFieldName = $this->entityMetadata->getEntityId();

        $rawDocument[Document::ID] = $rawDocument[$entityIdFieldName];

        return $this->objectManager->create($this->instanceName, ['data' => $rawDocument]);
    }
1135758
public function perform($targetDocument)
    {
        $pointer = new Pointer($targetDocument);
        $rootGet = array();
        $value = $this->getValue();

        try {
            $get = $pointer->get($this->getPath());
        } catch (NonexistentValueReferencedException $e) {
            $get = null;
        }

        $pointerParts = $this->getPointerParts();

        $rootPointer = $pointerParts[0];

        if (count($pointerParts) >= 2) {
            try {
                $rootGet = $pointer->get(Pointer::POINTER_CHAR . implode('/', array_slice($pointerParts, 0, -1)));
            } catch (NonexistentValueReferencedException $e) {
                return $targetDocument;
            }
        }

        $targetDocument = json_decode($targetDocument);

        $lastPointerPart = $pointerParts[count($pointerParts) - 1];
        $replacementValue = $this->getReplacementValue();

        if ($get === null && $lastPointerPart !== Pointer::LAST_ARRAY_ELEMENT_CHAR) {
            if (ctype_digit($lastPointerPart) && $lastPointerPart > count($rootGet)) {
                if ($rootPointer == $lastPointerPart && is_array($targetDocument)) {
                    if ((int) $lastPointerPart <= count($targetDocument) + 1) {
                        array_splice($targetDocument, $lastPointerPart, 0, $replacementValue);
                    }
                }
                return json_encode($targetDocument, JSON_UNESCAPED_UNICODE);
            }
            if (count($pointerParts) === 1) {
                if (is_array($targetDocument)) {
                    $targetDocument[$pointerParts[0]] = $value;
                } else {
                    $targetDocument->{$pointerParts[0]} = $value;
                }
            } elseif (count($pointerParts) > 1) {
                $augmentedDocument = &$targetDocument;
                foreach ($pointerParts as $pointerPart) {
                    if (is_array($augmentedDocument)) {
                        $augmentedDocument = &$augmentedDocument[$pointerPart];
                    } else {
                        $augmentedDocument = &$augmentedDocument->{$pointerPart};
                    }
                }
                $augmentedDocument = $value;
            }
        } else {
            $additionIndex = array_pop($pointerParts);
            $arrayEntryPath = '/' . implode('/', $pointerParts);

            try {
                $targetArray = $pointer->get($arrayEntryPath);
            } catch (NonexistentValueReferencedException $e) {
                $targetArray = null;
            }

            if (is_array($targetArray)) {
                if ($lastPointerPart === Pointer::LAST_ARRAY_ELEMENT_CHAR) {
                    $targetArray[] = $value;
                } else {
                    if (is_numeric($additionIndex)) {
                        array_splice($targetArray, $additionIndex, 0, $replacementValue);
                    } else {
                        $targetArray[$additionIndex] = $value;
                    }
                }
            }

            if (is_object($targetArray)) {
                $targetArray->{$additionIndex} = $value;
            }

            if (is_array($targetArray) || is_object($targetArray)) {
                $augmentedDocument = &$targetDocument;
                foreach ($pointerParts as $pointerPart) {
                    if (is_array($augmentedDocument)) {
                        $augmentedDocument = &$augmentedDocument[$pointerPart];
                    } else {
                        $augmentedDocument = &$augmentedDocument->{$pointerPart};
                    }
                }
                $augmentedDocument = $targetArray;
            }

            if ($targetArray === null) {
                if (is_numeric($additionIndex) && count($targetDocument) > 0) {
                    array_splice($targetDocument, $additionIndex, 0, $replacementValue);
                } else {
                    $targetDocument->{$additionIndex} = $value;
                }
            }
        }

        return json_encode($targetDocument, JSON_UNESCAPED_UNICODE);
    }
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;
    }
1347154
public function create(string $uri, string $content): PhpDocument
    {
        return new PhpDocument(
            $uri,
            $content,
            $this->projectIndex->getIndexForUri($uri),
            $this->parser,
            $this->docBlockFactory,
            $this->definitionResolver
        );
    }
1069501
public function fromString($xmlString)
    {
        $xml = $this->createDomDocument();
        $xml->loadXml($xmlString);

        return new Document($xml);
    }
1294161
public static function fromString($documentString)
    {
        $document = new MimeDocument($documentString);

        $lines = explode("\n", $documentString);

        $boundary = false;

        $nextPartLines = [];

        $firstBoundaryFound = false;
        $mimeMessage = "";

        foreach ($lines as $line) {
            $line = trim($line);

            if (!$boundary) {
                if (preg_match("/Content-Type: (multipart\/.+);\s+boundary=\"?([^\"]+)\"?/i", $line, $match)) {
                    $document->boundary = $match[2];
                    $document->setContentType($match[1]);
                    $boundary = $match[2];
                    continue;
                }
            } else {
                if ($line == "--" . $boundary . "--") {
                    $part = MimePart::fromLines($nextPartLines);
                    $document->addPart($part);
                    break;
                }

                if ($line == "--" . $boundary) {
                    if (!$firstBoundaryFound) {
                        $firstBoundaryFound = true;
                    } else {
                        $part = MimePart::fromLines($nextPartLines);
                        $document->addPart($part);
                        $nextPartLines = [];
                    }
                } else {
                    if ($firstBoundaryFound) {
                        $nextPartLines[] = $line;
                    } else {
                        $mimeMessage .= $line . "\r\n";
                    }
                }
            }
        }

        $document->setMessage(trim($mimeMessage));

        return $document;
    }
377480
public function getDocument($input)
    {
        $nodeMap = new JsonObject();
        $nodeMap->{'-' . JsonLD::DEFAULT_GRAPH} = new JsonObject();
        $this->generateNodeMap($nodeMap, $input);

        // We need to keep track of blank nodes as they are renamed when
        // inserted into the Document
        $nodes = array();

        if (null === $this->documentFactory) {
            $this->documentFactory = new DefaultDocumentFactory();
        }

        $document = $this->documentFactory->createDocument($this->baseIri);

        foreach ($nodeMap as $graphName => &$nodes) {
            $graphName = substr($graphName, 1);
            if (JsonLD::DEFAULT_GRAPH === $graphName) {
                $graph = $document->getGraph();
            } else {
                $graph = $document->createGraph($graphName);
            }

            foreach ($nodes as $id => &$item) {
                $node = $graph->createNode($item->{'@id'}, true);
                unset($item->{'@id'});

                // Process node type as it needs to be handled differently than
                // other properties
                // TODO Could this be avoided by enforcing rdf:type instead of @type?
                if (property_exists($item, '@type')) {
                    foreach ($item->{'@type'} as $type) {
                        $node->addType($graph->createNode($type), true);
                    }
                    unset($item->{'@type'});
                }

                foreach ($item as $property => $values) {
                    foreach ($values as $value) {
                        if (property_exists($value, '@value')) {
                            $node->addPropertyValue($property, Value::fromJsonLd($value));
                        } elseif (property_exists($value, '@id')) {
                            $node->addPropertyValue(
                                $property,
                                $graph->createNode($value->{'@id'}, true)
                            );
                        } else {
                            // TODO Handle lists
                            throw new \Exception('Lists are not supported by getDocument() yet');
                        }
                    }
                }
            }
        }


        unset($nodeMap);

        return $document;
    }
116702
public function parse($path)
    {
        $rawDocument = $this->loadDocument($path);
        list($rawMetadata, $rawContent) = $this->splitDocument($rawDocument);
        return $this->createDocument($rawDocument, $rawMetadata, $rawContent);
    }
637644
public function getDocument()
    {
        $doc = new Document();
        $doc->setData($this->getSource());
        $hit = $this->getHit();
        unset($hit['_source']);
        unset($hit['_explanation']);
        unset($hit['highlight']);
        unset($hit['_score']);
        $doc->setParams($hit);

        return $doc;
    }
929795
protected function getDocuments($locale)
    {
        $propertyEncoder = $this->getContainer()->get('sulu_document_manager.property_encoder');
        $documentManager = $this->getContainer()->get('sulu_document_manager.document_manager');

        $sql2 = sprintf(
            'SELECT * FROM [nt:unstructured] AS a WHERE [jcr:mixinTypes] = "sulu:article" AND [%s] IS NOT NULL',
            $propertyEncoder->localizedSystemName('template', $locale)
        );

        return $documentManager->createQuery($sql2, $locale, ['load_ghost_content' => false])->execute();
    }
863673
protected function transcodeDataToDocument($document, $identifier)
    {
        if (!$document instanceof Document) {

            if (is_object($document)) {
                if (get_class($document) == 'stdClass') {
                    $document = (array) $document;
                } else {
                    if ($document instanceof \JsonSerializable) {
                        $document = json_encode($document);
                    } elseif (method_exists($document, 'toArray')) {
                        $document = $document->toArray();
                    } else {
                        throw new \LogicException(
                            'The given object representing a document value eihter have to implement the JsonSerializable'.
                            'interface or a toArray() method in order to be stored it in elasticsearch.',
                            AdaptorException::DATA_UNSERIALIZABLE
                        );
                    }
                }
            }

            $document = $this->decorator->normalizeValue($document);

            Assertion::notEmpty($document, 'The document data may not be empty.');

            $document = new Document($identifier, $document);
        }

        return $document;
    }
1174279
private function doMerge(object $document, array &$visited, ?object $prevManagedCopy = null, ?array $assoc = null) : object
    {
        $oid = spl_object_hash($document);

        if (isset($visited[$oid])) {
            return $visited[$oid]; // Prevent infinite recursion
        }

        $visited[$oid] = $document; // mark visited

        $class = $this->dm->getClassMetadata(get_class($document));

        /* First we assume DETACHED, although it can still be NEW but we can
         * avoid an extra DB round trip this way. If it is not MANAGED but has
         * an identity, we need to fetch it from the DB anyway in order to
         * merge. MANAGED documents are ignored by the merge operation.
         */
        $managedCopy = $document;

        if ($this->getDocumentState($document, self::STATE_DETACHED) !== self::STATE_MANAGED) {
            if ($document instanceof GhostObjectInterface && ! $document->isProxyInitialized()) {
                $document->initializeProxy();
            }

            $identifier = $class->getIdentifier();
            // We always have one element in the identifier array but it might be null
            $id          = $identifier[0] !== null ? $class->getIdentifierObject($document) : null;
            $managedCopy = null;

            // Try to fetch document from the database
            if (! $class->isEmbeddedDocument && $id !== null) {
                $managedCopy = $this->dm->find($class->name, $id);

                // Managed copy may be removed in which case we can't merge
                if ($managedCopy && $this->getDocumentState($managedCopy) === self::STATE_REMOVED) {
                    throw new InvalidArgumentException('Removed entity detected during merge. Cannot merge with a removed entity.');
                }

                if ($managedCopy instanceof GhostObjectInterface && ! $managedCopy->isProxyInitialized()) {
                    $managedCopy->initializeProxy();
                }
            }

            if ($managedCopy === null) {
                // Create a new managed instance
                $managedCopy = $class->newInstance();
                if ($id !== null) {
                    $class->setIdentifierValue($managedCopy, $id);
                }
                $this->persistNew($class, $managedCopy);
            }

            if ($class->isVersioned) {
                $managedCopyVersion = $class->reflFields[$class->versionField]->getValue($managedCopy);
                $documentVersion    = $class->reflFields[$class->versionField]->getValue($document);

                // Throw exception if versions don't match
                if ($managedCopyVersion !== $documentVersion) {
                    throw LockException::lockFailedVersionMissmatch($document, $documentVersion, $managedCopyVersion);
                }
            }

            // Merge state of $document into existing (managed) document
            foreach ($class->reflClass->getProperties() as $prop) {
                $name = $prop->name;
                $prop->setAccessible(true);
                if (! isset($class->associationMappings[$name])) {
                    if (! $class->isIdentifier($name)) {
                        $prop->setValue($managedCopy, $prop->getValue($document));
                    }
                } else {
                    $assoc2 = $class->associationMappings[$name];

                    if ($assoc2['type'] === 'one') {
                        $other = $prop->getValue($document);

                        if ($other === null) {
                            $prop->setValue($managedCopy, null);
                        } elseif ($other instanceof GhostObjectInterface && ! $other->isProxyInitialized()) {
                            // Do not merge fields marked lazy that have not been fetched
                            continue;
                        } elseif (! $assoc2['isCascadeMerge']) {
                            if ($this->getDocumentState($other) === self::STATE_DETACHED) {
                                $targetDocument = $assoc2['targetDocument'] ?? get_class($other);
                                /** @var ClassMetadata $targetClass */
                                $targetClass = $this->dm->getClassMetadata($targetDocument);
                                $relatedId   = $targetClass->getIdentifierObject($other);

                                if ($targetClass->subClasses) {
                                    $other = $this->dm->find($targetClass->name, $relatedId);
                                } else {
                                    $other = $this
                                        ->dm
                                        ->getProxyFactory()
                                        ->getProxy($targetClass, $relatedId);
                                    $this->registerManaged($other, $relatedId, []);
                                }
                            }

                            $prop->setValue($managedCopy, $other);
                        }
                    } else {
                        $mergeCol = $prop->getValue($document);

                        if ($mergeCol instanceof PersistentCollectionInterface && ! $mergeCol->isInitialized() && ! $assoc2['isCascadeMerge']) {
                            /* Do not merge fields marked lazy that have not
                             * been fetched. Keep the lazy persistent collection
                             * of the managed copy.
                             */
                            continue;
                        }

                        $managedCol = $prop->getValue($managedCopy);

                        if (! $managedCol) {
                            $managedCol = $this->dm->getConfiguration()->getPersistentCollectionFactory()->create($this->dm, $assoc2, null);
                            $managedCol->setOwner($managedCopy, $assoc2);
                            $prop->setValue($managedCopy, $managedCol);
                            $this->originalDocumentData[$oid][$name] = $managedCol;
                        }

                        /* Note: do not process association's target documents.
                         * They will be handled during the cascade. Initialize
                         * and, if necessary, clear $managedCol for now.
                         */
                        if ($assoc2['isCascadeMerge']) {
                            $managedCol->initialize();

                            // If $managedCol differs from the merged collection, clear and set dirty
                            if (! $managedCol->isEmpty() && $managedCol !== $mergeCol) {
                                $managedCol->unwrap()->clear();
                                $managedCol->setDirty(true);

                                if ($assoc2['isOwningSide'] && $class->isChangeTrackingNotify()) {
                                    $this->scheduleForSynchronization($managedCopy);
                                }
                            }
                        }
                    }
                }

                if (! $class->isChangeTrackingNotify()) {
                    continue;
                }

                // Just treat all properties as changed, there is no other choice.
                $this->propertyChanged($managedCopy, $name, null, $prop->getValue($managedCopy));
            }

            if ($class->isChangeTrackingDeferredExplicit()) {
                $this->scheduleForSynchronization($document);
            }
        }

        if ($prevManagedCopy !== null) {
            $assocField = $assoc['fieldName'];
            $prevClass  = $this->dm->getClassMetadata(get_class($prevManagedCopy));

            if ($assoc['type'] === 'one') {
                $prevClass->reflFields[$assocField]->setValue($prevManagedCopy, $managedCopy);
            } else {
                $prevClass->reflFields[$assocField]->getValue($prevManagedCopy)->add($managedCopy);

                if ($assoc['type'] === 'many' && isset($assoc['mappedBy'])) {
                    $class->reflFields[$assoc['mappedBy']]->setValue($managedCopy, $prevManagedCopy);
                }
            }
        }

        // Mark the managed copy visited as well
        $visited[spl_object_hash($managedCopy)] = $managedCopy;

        $this->cascadeMerge($document, $managedCopy, $visited);

        return $managedCopy;
    }
935043
private function newInstance(DocumentMetadata $class)
    {
        $document = $class->newInstance();

        // inject ObjectManager upon refresh.
        if ($document instanceof ObjectManagerAware) {
            $document->injectObjectManager($this->manager, $class);
        }

        return $document;
    }
1133483
public static function createXmlDocumentFromStr($xml, $docOptions = XMLUTIL_OPT_DONT_FIX_AMPERSAND)
    {
        set_error_handler(function ($number, $error) {
            $matches = [];
            if (preg_match('/^DOMDocument::loadXML\(\): (.+)$/', $error, $matches) === 1) {
                throw new \InvalidArgumentException("[Err #$number] ".$matches[1]);
            }
        });

        $xmldoc = self::createXmlDocument($docOptions);

        $xmlFixed = XmlUtil::fixXmlHeader($xml);
        if (($docOptions & XMLUTIL_OPT_DONT_FIX_AMPERSAND) != XMLUTIL_OPT_DONT_FIX_AMPERSAND) {
            $xmlFixed = str_replace("&amp;", "&", $xmlFixed);
        }

        $xmldoc->loadXML($xmlFixed);

        XmlUtil::extractNamespaces($xmldoc);

        restore_error_handler();

        return $xmldoc;
    }
514661
public function createIdentifier($document, $unmarshal = false)
    {
        $index     = $this->getIndex();
        $hashKey   = $index->getHashKey();
        $hashValue = $hashKey->getPropertyMetadata()->getValue($document);

        if ($unmarshal) {
            $hashValue = $hashKey->getType()->convertToPHPValue($hashValue);
        }

        if (!$index->isComposite()) {
            return $this->createIdentifierFromValues($hashValue);
        }

        $rangeKey   = $index->getRangeKey();
        $rangeValue = $rangeKey->getPropertyMetadata()->getValue($document);

        if ($unmarshal) {
            $rangeValue = $rangeKey->getType()->convertToPHPValue($rangeValue);
        }

        return $this->createIdentifierFromValues($hashValue, $rangeValue);
    }
324664
public function createInverseDocumentFrequency()
    {
        $documentCount = $this->getTotalDocumentCount();
        $inverseDocumentFrequency = new InverseDocumentFrequency($this->getSearchDbHandle(), $documentCount);
        $inverseDocumentFrequency->execute();
    }
630572
private function getDocument(string $rawHTML): Document {
        $doc = new Document();
        $doc->html($rawHTML);

        return $doc;
    }