Esempio n. 1
0
 /**
  * {@inheritDoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $session = $this->getPhpcrSession();
     $dumperHelper = $this->getPhpcrConsoleDumperHelper();
     // node to dump
     $identifier = $input->getArgument('identifier');
     // whether to dump node uuid
     $options = array();
     $options['dump_uuids'] = $input->hasParameterOption('--identifiers');
     $options['ref_format'] = $input->getOption('ref-format');
     $options['show_props'] = $input->hasParameterOption('--props');
     $options['show_sys_nodes'] = $input->hasParameterOption('--sys-nodes');
     $options['max_line_length'] = $input->getOption('max_line_length');
     if (null !== $options['ref_format'] && !in_array($options['ref_format'], array('uuid', 'path'))) {
         throw new \Exception('The ref-format option must be set to either "path" or "uuid"');
     }
     $walker = $dumperHelper->getTreeWalker($output, $options);
     try {
         if (UUIDHelper::isUUID($identifier)) {
             $node = $session->getNodeByIdentifier($identifier);
         } else {
             $node = $session->getNode($identifier);
         }
         $walker->traverse($node, $input->getOption('depth'));
     } catch (RepositoryException $e) {
         if ($e instanceof PathNotFoundException || $e instanceof ItemNotFoundException) {
             $output->writeln("<error>Path '{$identifier}' does not exist</error>");
         } else {
             throw $e;
         }
         return 1;
     }
     return 0;
 }
Esempio n. 2
0
 public function testIsUUID()
 {
     $this->assertTrue(UUIDHelper::isUUID('550e8400-e29b-41d4-a716-446655440000'));
     $this->assertTrue(UUIDHelper::isUUID('00000000-0000-0000-C000-000000000046'));
     $this->assertFalse(UUIDHelper::isUUID('not a uuid'));
     $this->assertFalse(UUIDHelper::isUUID('123456'));
 }
 public function testCommandIdentifier()
 {
     $uuid = UUIDHelper::generateUUID();
     $this->dumperHelper->expects($this->once())->method('getTreeWalker')->will($this->returnValue($this->treeWalker));
     $this->session->expects($this->once())->method('getNodeByIdentifier')->with($uuid)->will($this->returnValue($this->node1));
     $this->treeWalker->expects($this->once())->method('traverse')->with($this->node1);
     $this->executeCommand('phpcr:node:dump', array('identifier' => $uuid));
 }
 /**
  * {@inheritdoc}
  */
 public function createNodeForDocument($document, NodeInterface $parentNode, $name)
 {
     $metadata = $this->metadataFactory->getMetadataForClass(get_class($document));
     $node = $parentNode->addNode($name);
     $node->addMixin($metadata->getPhpcrType());
     $node->setProperty('jcr:uuid', UUIDHelper::generateUUID());
     return $node;
 }
Esempio n. 5
0
 private function processNode(Node $node)
 {
     if (false === $node->hasProperty(Storage::JCR_UUID)) {
         return;
     }
     $jcrUuid = UUIDHelper::generateUUID();
     $node->setProperty(Storage::JCR_UUID, $jcrUuid, 'String');
 }
 /**
  * @covers Doctrine\ODM\PHPCR\DocumentManager::findTranslation
  */
 public function testFindTranslation()
 {
     $fakeUuid = \PHPCR\Util\UUIDHelper::generateUUID();
     $session = $this->getMockForAbstractClass('PHPCR\\SessionInterface', array('getNodeByIdentifier'));
     $session->expects($this->once())->method('getNodeByIdentifier')->will($this->throwException(new \PHPCR\ItemNotFoundException(sprintf('403: %s', $fakeUuid))));
     $config = new \Doctrine\ODM\PHPCR\Configuration();
     $dm = DocumentManager::create($session, $config);
     $nonExistent = $dm->findTranslation(null, $fakeUuid, 'en');
     $this->assertNull($nonExistent);
 }
Esempio n. 7
0
 private function getOrCreateInternalUuid($path)
 {
     if (!$this->pathRegistry->hasPath($path)) {
         $internalUuid = UUIDHelper::generateUUID();
     } else {
         $internalUuid = $this->pathRegistry->getUuid($path);
     }
     if (!$internalUuid) {
         throw new \RuntimeException('Failed to determine internal UUID');
     }
     return $internalUuid;
 }
Esempio n. 8
0
 public function reverseTransform($uuid)
 {
     if (!$uuid) {
         return;
     }
     if (!UUIDHelper::isUuid($uuid)) {
         throw new TransformationFailedException(sprintf('Given UUID is not a UUID, given: "%s"', $uuid));
     }
     $document = $this->documentManager->find($uuid);
     if (null === $document) {
         throw new TransformationFailedException(sprintf('Could not find document with UUID "%s"', $uuid));
     }
     return $document;
 }
 private function resolveSiblingName($siblingId, NodeInterface $parentNode, NodeInterface $node)
 {
     if (null === $siblingId) {
         return;
     }
     $siblingPath = $siblingId;
     if (UUIDHelper::isUUID($siblingId)) {
         $siblingPath = $this->nodeManager->find($siblingId)->getPath();
     }
     if ($siblingPath !== null && PathHelper::getParentPath($siblingPath) !== $parentNode->getPath()) {
         throw new DocumentManagerException(sprintf('Cannot reorder documents which are not siblings. Trying to reorder "%s" to "%s"', $node->getPath(), $siblingPath));
     }
     if (null !== $siblingPath) {
         return PathHelper::getNodeName($siblingPath);
     }
     return $node->getName();
 }
 public function testFindManyWithNonExistingUuuid()
 {
     $user = new TestUser();
     $user->username = '******';
     $user->id = '/functional/test';
     $this->dm->persist($user);
     $this->dm->flush();
     $this->dm->clear();
     $actualUuid = $user->uuid;
     $unusedUuid = UUIDHelper::generateUUID();
     $this->assertNotNull($this->dm->find(get_class($user), $user->id));
     $this->assertNotNull($this->dm->find(get_class($user), $actualUuid));
     $this->assertNull($this->dm->find(get_class($user), $unusedUuid));
     $uuids = array($actualUuid, $unusedUuid);
     $documents = $this->dm->findMany(get_class($user), $uuids);
     $this->assertEquals(1, count($documents));
 }
Esempio n. 11
0
 public function testCreate()
 {
     $refTestObj = new RefTestObj();
     $refRefTestObj = new RefRefTestObj();
     $refTestObj->id = "/functional/refTestObj";
     $refRefTestObj->id = "/functional/refRefTestObj";
     $refRefTestObj->name = "referenced";
     $refTestObj->reference = $refRefTestObj;
     $this->dm->persist($refTestObj);
     $this->dm->flush();
     $this->dm->clear();
     $this->assertTrue($this->session->getNode('/functional')->hasNode('refRefTestObj'));
     $refRefTestNode = $this->session->getNode('/functional/refRefTestObj');
     $this->assertEquals('referenced', $refRefTestNode->getProperty('name')->getString());
     $refTestNode = $this->session->getNode('/functional/refTestObj');
     $this->assertTrue($refTestNode->hasProperty('myReference'));
     $this->assertEquals($refRefTestNode->getIdentifier(), $refTestNode->getProperty('myReference')->getString());
     $this->assertTrue(UUIDHelper::isUUID($refTestNode->getProperty('myReference')->getString()));
 }
Esempio n. 12
0
 public function execute(InputInterface $input, OutputInterface $output)
 {
     $session = $this->get('phpcr.session');
     $pathHelper = $this->get('helper.path');
     $path = $session->getAbsPath($input->getArgument('path'));
     $value = $input->getArgument('value');
     $type = $input->getOption('type');
     $nodePath = $pathHelper->getParentPath($path);
     $propName = $pathHelper->getNodeName($path);
     $nodes = $session->findNodes($nodePath);
     foreach ($nodes as $node) {
         $intType = null;
         if ($type) {
             $intType = PropertyType::valueFromName($type);
             if ($intType === PropertyType::REFERENCE || $intType === PropertyType::WEAKREFERENCE) {
                 // convert path to UUID
                 if (false === UUIDHelper::isUuid($value)) {
                     $path = $value;
                     try {
                         $targetNode = $session->getNode($path);
                         $value = $targetNode->getIdentifier();
                     } catch (PathNotFoundException $e) {
                     }
                     if (null === $value) {
                         throw new \InvalidArgumentException(sprintf('Node at path "%s" specified for reference is not referenceable', $path));
                     }
                 }
             }
         } else {
             try {
                 $property = $node->getProperty($propName);
                 $intType = $property->getType();
             } catch (PathNotFoundException $e) {
                 // property doesn't exist and no type specified, default to string
                 $intType = PropertyType::STRING;
             }
         }
         $node->setProperty($propName, $value, $intType);
     }
 }
 public function addNode($workspaceName, \DOMElement $node)
 {
     $properties = $this->getAttributes($node);
     $uuid = isset($properties['jcr:uuid']['value'][0]) ? (string) $properties['jcr:uuid']['value'][0] : UUIDHelper::generateUUID();
     $this->ids[$uuid] = $id = isset($this->expectedNodes[$uuid]) ? $this->expectedNodes[$uuid] : self::$idCounter++;
     $dom = new \DOMDocument('1.0', 'UTF-8');
     $phpcrNode = $dom->createElement('sv:node');
     foreach ($this->namespaces as $namespace => $uri) {
         $phpcrNode->setAttribute('xmlns:' . $namespace, $uri);
     }
     $dom->appendChild($phpcrNode);
     foreach ($properties as $propertyName => $propertyData) {
         if ($propertyName == 'jcr:uuid') {
             continue;
         }
         if (!isset($this->jcrTypes[$propertyData['type']])) {
             throw new \InvalidArgumentException('"' . $propertyData['type'] . '" is not a valid JCR type.');
         }
         $phpcrNode->appendChild($this->createPropertyNode($workspaceName, $propertyName, $propertyData, $id, $dom, $phpcrNode));
     }
     list($parentPath, $childPath) = $this->getPath($node);
     $namespace = '';
     $name = $node->getAttributeNS($this->namespaces['sv'], 'name');
     if (count($parts = explode(':', $name, 2)) == 2) {
         list($namespace, $name) = $parts;
     }
     if ($namespace == 'jcr' && $name == 'root') {
         $id = 1;
         $childPath = '/';
         $parentPath = '';
         $name = '';
         $namespace = '';
     }
     $this->addRow('phpcr_nodes', array('id' => $id, 'path' => $childPath, 'parent' => $parentPath, 'local_name' => $name, 'namespace' => $namespace, 'workspace_name' => $workspaceName, 'identifier' => $uuid, 'type' => $properties['jcr:primaryType']['value'][0], 'props' => $dom->saveXML(), 'depth' => PathHelper::getPathDepth($childPath), 'sort_order' => $id - 2));
     return $this;
 }
Esempio n. 14
0
 /**
  * {@inheritdoc}
  */
 public function write(NodeInterface $node, PropertyInterface $property, $userId, $webspaceKey, $languageCode, $segmentKey)
 {
     $snippetReferences = [];
     $values = $property->getValue();
     $values = is_array($values) ? $values : [];
     foreach ($values as $value) {
         if ($value instanceof SnippetBridge) {
             $snippetReferences[] = $value->getUuid();
         } elseif (is_array($value) && array_key_exists('uuid', $value) && UUIDHelper::isUUID($value['uuid'])) {
             $snippetReferences[] = $value['uuid'];
         } elseif (UUIDHelper::isUUID($value)) {
             $snippetReferences[] = $value;
         } else {
             throw new \InvalidArgumentException(sprintf('Property value must either be a UUID or a Snippet, "%s" given.', gettype($value)));
         }
     }
     $node->setProperty($property->getName(), $snippetReferences, PropertyType::REFERENCE);
 }
Esempio n. 15
0
 private function setMixins(Mapping\ClassMetadata $metadata, NodeInterface $node)
 {
     if ($metadata->versionable === 'full') {
         $node->addMixin('mix:versionable');
     } else {
         if ($metadata->versionable === 'simple') {
             $node->addMixin('mix:simpleVersionable');
         }
         if ($metadata->referenceable) {
             $node->addMixin('mix:referenceable');
         }
     }
     // we manually set the uuid to allow creating referenced and referencing document without flush in between.
     if ($node->isNodeType('mix:referenceable') && !$node->hasProperty('jcr:uuid')) {
         // TODO do we need to check with the storage backend if the generated id really is unique?
         $node->setProperty('jcr:uuid', UUIDHelper::generateUUID());
     }
 }
 /**
  * Get the closure for the UUID generation.
  *
  * @since 1.1
  * @return callable a UUID generator
  */
 public function getUuidGenerator()
 {
     return isset($this->attributes['uuidGenerator']) ? $this->attributes['uuidGenerator'] : function () {
         return UUIDHelper::generateUUID();
     };
 }
Esempio n. 17
0
    /**
     * @return callable a uuid generator function.
     */
    protected function getUuidGenerator()
    {
        if (!$this->uuidGenerator) {
            $this->uuidGenerator = function() {
                return UUIDHelper::generateUUID();
            };
        }

        return $this->uuidGenerator;
    }
Esempio n. 18
0
 public function testLoadShallowStructureByNode()
 {
     $node = $this->session->getNode($this->snippet1OriginalPath);
     $snippet = $this->contentMapper->loadShallowStructureByNode($node, 'de', 'sulu_io');
     $this->assertEquals('animal', $snippet->getKey());
     $this->assertTrue(UUIDHelper::isUUID($snippet->getUuid()));
 }
Esempio n. 19
0
 /**
  * @return string a universally unique id.
  */
 protected function generateUuid()
 {
     return UUIDHelper::generateUUID();
 }
Esempio n. 20
0
    public function execute(InputInterface $input, OutputInterface $output)
    {
        $session = $this->get('phpcr.session');
        $path = $input->getArgument('path');
        if (UUIDHelper::isUUID($path)) {
            // If the node is a UUID, then just get it
            $node = $session->getNodeByIdentifier($path);
        } else {
            $path = $session->getAbsPath($path);
            // Otherwise it is a path which may or may not exist
            $parentPath = $this->get('helper.path')->getParentPath($path);
            $nodeName = $this->get('helper.path')->getNodeName($path);
            $type = $input->getOption('type');
            try {
                // if it exists, then great
                $node = $session->getNodeByPathOrIdentifier($path);
            } catch (PathNotFoundException $e) {
                // if it doesn't exist then we create it
                $parentNode = $session->getNode($parentPath);
                $node = $parentNode->addNode($nodeName, $type);
            }
        }
        $editor = $this->get('helper.editor');
        $dialog = $this->get('helper.question');
        $skipBinary = true;
        $noRecurse = true;
        // for now we only support YAML
        $encoders = [new YamlEncoder()];
        $nodeNormalizer = new NodeNormalizer();
        $serializer = new Serializer([$nodeNormalizer], $encoders);
        $outStr = $serializer->serialize($node, 'yaml');
        $tryAgain = false;
        $message = '';
        $error = '';
        $notes = implode("\n", $nodeNormalizer->getNotes());
        do {
            $message = '';
            if ($error) {
                $template = <<<'EOT'
Error encounred:
%s

EOT;
                $message .= sprintf($template, $error);
            }
            if ($notes) {
                $template = <<<'EOT'
NOTE:
%s

EOT;
                $message .= sprintf($template, $notes);
            }
            // string pass to editor
            if ($message) {
                $inStr = $editor->fromStringWithMessage($outStr, $message, '# ', 'yml');
            } else {
                $inStr = $editor->fromString($outStr, 'yml');
            }
            try {
                $norm = $serializer->deserialize($inStr, 'PHPCR\\NodeInterface', 'yaml', ['node' => $node]);
                $tryAgain = false;
            } catch (\Exception $e) {
                $error = $e->getMessage();
                $output->writeln('<error>' . $error . '</error>');
                if (false === $input->getOption('no-interaction')) {
                    $tryAgain = $dialog->ask($input, $output, new ConfirmationQuestion('Do you want to try again? (y/n)'));
                }
                $outStr = $inStr;
            }
        } while ($tryAgain == true);
        if ($error) {
            return 1;
        }
        return 0;
    }
 public function testGetRoutesByNamesUuid()
 {
     $uuid1 = UUIDHelper::generateUUID();
     $uuid2 = UUIDHelper::generateUUID();
     $paths = array($uuid1, $uuid2);
     $route1 = new Route('/test-route');
     $route2 = new Route('/other-route');
     $routes = new ArrayCollection();
     $routes->set($uuid1, $route1);
     $routes->set($uuid2, $route2);
     $this->dmMock->expects($this->once())->method('findMany')->with(null, $paths)->will($this->returnValue($routes));
     $uow = $this->buildMock('Doctrine\\ODM\\PHPCR\\UnitOfWork');
     $this->dmMock->expects($this->any())->method('getUnitOfWork')->will($this->returnValue($uow));
     $uow->expects($this->at(0))->method('getDocumentId')->with($route1)->will($this->returnValue('/cms/routes/test-route'));
     $uow->expects($this->at(1))->method('getDocumentId')->with($route2)->will($this->returnValue('/cms/routes/other-route'));
     $this->candidatesMock->expects($this->at(0))->method('isCandidate')->with('/cms/routes/test-route')->will($this->returnValue(true));
     $this->candidatesMock->expects($this->at(1))->method('isCandidate')->with('/cms/routes/other-route')->will($this->returnValue(false));
     $routeProvider = new RouteProvider($this->managerRegistryMock, $this->candidatesMock);
     $routeProvider->setManagerName('default');
     $routes = $routeProvider->getRoutesByNames($paths);
     $this->assertCount(1, $routes);
 }
 /**
  * Get subject
  *
  * Overridden to allow a broader set of valid characters in the ID, and
  * if the ID is not a UUID, to call absolutizePath on the ID.
  *
  * @return mixed
  */
 public function getSubject()
 {
     if ($this->subject === null && $this->request) {
         $id = $this->request->get($this->getIdParameter());
         if (!preg_match('#^[0-9A-Za-z/\\-_]+$#', $id)) {
             $this->subject = false;
         } else {
             if (!UUIDHelper::isUUID($id)) {
                 $id = PathHelper::absolutizePath($id, '/');
             }
             $this->subject = $this->getModelManager()->find($this->getClass(), $id);
         }
     }
     return $this->subject;
 }
Esempio n. 23
0
 /**
  * TODO: we should move that into the common Jackalope BaseTransport or as new method of NodeType
  * it will be helpful for other implementations
  *
  * Validate this node with the nodetype and generate not yet existing
  * autogenerated properties as necessary
  *
  * @param Node     $node
  * @param NodeType $def
  */
 private function validateNode(Node $node, NodeType $def)
 {
     foreach ($def->getDeclaredChildNodeDefinitions() as $childDef) {
         /* @var $childDef \PHPCR\NodeType\NodeDefinitionInterface */
         if (!$node->hasNode($childDef->getName())) {
             if ('*' === $childDef->getName()) {
                 continue;
             }
             if ($childDef->isMandatory() && !$childDef->isAutoCreated()) {
                 throw new RepositoryException("Child " . $childDef->getName() . " is mandatory, but is not present while " . "saving " . $def->getName() . " at " . $node->getPath());
             }
             if ($childDef->isAutoCreated()) {
                 throw new NotImplementedException("Auto-creation of child node '" . $def->getName() . "#" . $childDef->getName() . "' is not yet supported in DoctrineDBAL transport.");
             }
         }
     }
     foreach ($def->getDeclaredPropertyDefinitions() as $propertyDef) {
         /* @var $propertyDef \PHPCR\NodeType\PropertyDefinitionInterface */
         if ('*' == $propertyDef->getName()) {
             continue;
         }
         if (!$node->hasProperty($propertyDef->getName())) {
             if ($propertyDef->isMandatory() && !$propertyDef->isAutoCreated()) {
                 throw new RepositoryException("Property " . $propertyDef->getName() . " is mandatory, but is not present while " . "saving " . $def->getName() . " at " . $node->getPath());
             }
             if ($propertyDef->isAutoCreated()) {
                 switch ($propertyDef->getName()) {
                     case 'jcr:uuid':
                         $value = UUIDHelper::generateUUID();
                         break;
                     case 'jcr:createdBy':
                     case 'jcr:lastModifiedBy':
                         $value = $this->credentials->getUserID();
                         break;
                     case 'jcr:created':
                     case 'jcr:lastModified':
                         $value = new \DateTime();
                         break;
                     case 'jcr:etag':
                         // TODO: http://www.day.com/specs/jcr/2.0/3_Repository_Model.html#3.7.12.1%20mix:etag
                         $value = 'TODO: generate from binary properties of this node';
                         break;
                     default:
                         $defaultValues = $propertyDef->getDefaultValues();
                         if ($propertyDef->isMultiple()) {
                             $value = $defaultValues;
                         } elseif (isset($defaultValues[0])) {
                             $value = $defaultValues[0];
                         } else {
                             // When implementing versionable or activity, we need to handle more properties explicitly
                             throw new RepositoryException('No default value for autocreated property ' . $propertyDef->getName() . ' at ' . $node->getPath());
                         }
                 }
                 $node->setProperty($propertyDef->getName(), $value, $propertyDef->getRequiredType());
             }
         }
     }
     foreach ($node->getProperties() as $property) {
         $this->assertValidProperty($property);
     }
 }
Esempio n. 24
0
 /**
  * {@inheritDoc}
  *
  * @throws InvalidItemStateException
  * @throws NoSuchWorkspaceException
  *
  * @api
  */
 public function getNode()
 {
     $this->checkState();
     $values = $this->isMultiple() ? $this->value : array($this->value);
     $results = array();
     switch ($this->type) {
         case PropertyType::REFERENCE:
             $results = $this->getReferencedNodes($values, false);
             break;
         case PropertyType::WEAKREFERENCE:
             $results = $this->getReferencedNodes($values, true);
             break;
         case PropertyType::STRING:
             foreach ($values as $value) {
                 if (UUIDHelper::isUUID($value)) {
                     $results[] = $this->objectManager->getNodeByIdentifier($value);
                 } else {
                     $results[] = $this->objectManager->getNode($value, $this->parentPath);
                 }
             }
             break;
         case PropertyType::PATH:
         case PropertyType::NAME:
             foreach ($values as $value) {
                 // OPTIMIZE: use objectManager->getNodes instead of looping (but paths need to be absolute then)
                 $results[] = $this->objectManager->getNode($value, $this->parentPath);
             }
             break;
         default:
             throw new ValueFormatException('Property is not a REFERENCE, WEAKREFERENCE or PATH (or convertible to PATH)');
     }
     return $this->isMultiple() ? $results : reset($results);
 }
Esempio n. 25
0
 public function testGetReferencedUuids()
 {
     $pageNode = $this->session->getNode('/cmf/sulu_io/contents/hotels');
     $pageStructure = $this->contentMapper->loadByNode($pageNode, 'en', 'sulu_io', true, false, false);
     $property = $pageStructure->getProperty('hotels');
     $uuids = $this->contentType->getReferencedUuids($property);
     $this->assertCount(2, $uuids);
     foreach ($uuids as $uuid) {
         $this->assertTrue(UUIDHelper::isUuid($uuid));
     }
 }
Esempio n. 26
0
 /**
  * Get the database primary key for node.
  *
  * @param string $identifier    Path of the identifier
  * @param string $workspaceName To overwrite the current workspace
  *
  * @return bool|string The database id
  */
 private function getSystemIdForNode($identifier, $workspaceName = null)
 {
     if (null === $workspaceName) {
         $workspaceName = $this->workspaceName;
     }
     if (UUIDHelper::isUUID($identifier)) {
         $query = 'SELECT id FROM phpcr_nodes WHERE identifier = ? AND workspace_name = ?';
     } else {
         if ($this->getConnection()->getDriver() instanceof \Doctrine\DBAL\Driver\PDOMySql\Driver) {
             $query = 'SELECT id FROM phpcr_nodes WHERE path COLLATE utf8_bin = ? AND workspace_name = ?';
         } else {
             $query = 'SELECT id FROM phpcr_nodes WHERE path = ? AND workspace_name = ?';
         }
     }
     $nodeId = $this->getConnection()->fetchColumn($query, array($identifier, $workspaceName));
     return $nodeId ?: false;
 }
Esempio n. 27
0
 public function findNodes($patternOrId)
 {
     if (true === UUIDHelper::isUUID($patternOrId)) {
         return $this->getNodeByIdentifier($patternOrId);
     }
     $res = $this->finder->find($this->getAbsPath($patternOrId));
     return $res;
 }
Esempio n. 28
0
 /**
  * {@inheritDoc}
  */
 public function getRoutesByNames($names = null)
 {
     if (null === $names) {
         return $this->getAllRoutes();
     }
     $candidates = array();
     foreach ($names as $key => $name) {
         if (UUIDHelper::isUUID($name) || $this->candidatesStrategy->isCandidate($name)) {
             $candidates[$key] = $name;
         }
     }
     if (!$candidates) {
         return array();
     }
     /** @var $dm DocumentManager */
     $dm = $this->getObjectManager();
     $documents = $dm->findMany($this->className, $candidates);
     foreach ($documents as $key => $document) {
         if (UUIDHelper::isUUID($key) && !$this->candidatesStrategy->isCandidate($this->getObjectManager()->getUnitOfWork()->getDocumentId($document))) {
             // this uuid pointed out of our path. can only determine after fetching the document
             unset($documents[$key]);
         }
         if (!$document instanceof SymfonyRoute) {
             // we follow the logic of DocumentManager::findMany and do not throw an exception
             unset($documents[$key]);
         }
     }
     return $documents;
 }
Esempio n. 29
0
 /**
  * Persist new document, marking it managed and generating the id and the node.
  *
  * This method is either called through `DocumentManager#persist()` or during `DocumentManager#flush()`,
  * when persistence by reachability is applied.
  *
  * @param ClassMetadata $class
  * @param object        $document
  */
 public function persistNew(ClassMetadata $class, $document, $overrideIdGenerator = null, $parent = null)
 {
     if ($invoke = $this->eventListenersInvoker->getSubscribedSystems($class, Event::prePersist)) {
         $this->eventListenersInvoker->invoke($class, Event::prePersist, $document, new LifecycleEventArgs($document, $this->dm), $invoke);
     }
     $generator = $this->getIdGenerator($overrideIdGenerator ? $overrideIdGenerator : $class->idGenerator);
     $id = $generator->generate($document, $class, $this->dm, $parent);
     $this->registerDocument($document, $id);
     if (!$generator instanceof AssignedIdGenerator) {
         $class->setIdentifierValue($document, $id);
     }
     // If the UUID is mapped, generate it early resp. validate if already present.
     $uuidFieldName = $class->getUuidFieldName();
     if ($uuidFieldName) {
         $existingUuid = $class->getFieldValue($document, $uuidFieldName);
         if (!$existingUuid) {
             $class->setFieldValue($document, $uuidFieldName, $this->generateUuid());
         } elseif (!UUIDHelper::isUUID($existingUuid)) {
             throw RuntimeException::invalidUuid($id, ClassUtils::getClass($document), $existingUuid);
         }
     }
 }
Esempio n. 30
0
 /**
  * Load the document from the content repository in the given language.
  * If $fallback is set to true, then the language chooser strategy is used to load the best suited
  * language for the translatable fields.
  *
  * If no translations can be found either using the fallback mechanism or not, an error is thrown.
  *
  * Note that this will be the same object as you got with a previous find/findTranslation call - we can't
  * allow copies of objects to exist
  *
  * @param $className
  * @param $id
  * @param $locale The language to try to load
  * @param bool $fallback Set to true if the language fallback mechanism should be used
  * @return object
  */
 public function findTranslation($className, $id, $locale, $fallback = true)
 {
     try {
         $node = UUIDHelper::isUUID($id) ? $this->session->getNodeByIdentifier($id) : $this->session->getNode($id);
     } catch (\PHPCR\PathNotFoundException $e) {
         return null;
     }
     $hints = array('locale' => $locale, 'fallback' => $fallback);
     return $this->unitOfWork->createDocument($className, $node, $hints);
 }