public function testSaveTranslation() { // First save some translations $data = array(); $data['topic'] = 'Some interesting subject'; $data['text'] = 'Lorem ipsum...'; $node = $this->getTestNode(); $strategy = new ChildTranslationStrategy($this->dm); $strategy->saveTranslation($data, $node, $this->metadata, 'en'); // Save translation in another language $data['topic'] = 'Un sujet intéressant'; $strategy->saveTranslation($data, $node, $this->metadata, 'fr'); $this->dm->getPhpcrSession()->save(); // Then test we have what we expect in the content repository $node_en = $this->session->getNode($this->nodeNameForLocale('en')); $node_fr = $this->session->getNode($this->nodeNameForLocale('fr')); $this->assertTrue($node_en->hasProperty('topic')); $this->assertTrue($node_fr->hasProperty('topic')); $this->assertTrue($node_en->hasProperty('text')); $this->assertTrue($node_fr->hasProperty('text')); $this->assertFalse($node_fr->hasProperty('author')); $this->assertFalse($node_en->hasProperty('author')); $this->assertEquals('Some interesting subject', $node_en->getPropertyValue('topic')); $this->assertEquals('Un sujet intéressant', $node_fr->getPropertyValue('topic')); $this->assertEquals('Lorem ipsum...', $node_en->getPropertyValue('text')); $this->assertEquals('Lorem ipsum...', $node_fr->getPropertyValue('text')); }
/** * {@inheritdoc} */ public function execute(InputInterface $input, OutputInterface $output) { $webspaceKey = $input->getArgument('webspaceKey'); $locale = $input->getArgument('locale'); $basePath = $input->getOption('base-path'); $dryRun = $input->getOption('dry-run'); $this->session = $this->getContainer()->get('doctrine_phpcr')->getManager()->getPhpcrSession(); $this->sessionManager = $this->getContainer()->get('sulu.phpcr.session'); $this->output = $output; $path = $this->sessionManager->getRoutePath($webspaceKey, $locale); $relativePath = $basePath !== null ? '/' . ltrim($basePath, '/') : '/'; $fullPath = rtrim($path . $relativePath, '/'); if (!$this->session->nodeExists($fullPath)) { $this->output->write('<error>Resource-Locator "' . $relativePath . '" not found</error>'); return; } $node = $this->session->getNode($fullPath); $this->cleanup($node, $path, $dryRun); if (false === $dryRun) { $this->output->writeln('<info>Saving ...</info>'); $this->session->save(); $this->output->writeln('<info>Done</info>'); } else { $this->output->writeln('<info>Dry run complete</info>'); } }
/** * {@inheritDoc} */ protected function getNode(array $pathSegments) { $absPath = '/' . implode('/', $pathSegments); try { return $this->session->getNode($absPath); } catch (\PHPCR\PathNotFoundException $e) { return null; } }
/** * Find a document with the given path or UUID. * * @param string $identifier UUID or path * * @return NodeInterface * * @throws DocumentNotFoundException */ public function find($identifier) { try { if (UUIDHelper::isUUID($identifier)) { return $this->session->getNodeByIdentifier($identifier); } return $this->session->getNode($identifier); } catch (RepositoryException $e) { throw new DocumentNotFoundException(sprintf('Could not find document with ID or path "%s"', $identifier), null, $e); } }
private function initPages() { $this->team = $this->savePage('simple', ['title' => 'Team', 'url' => '/team'], $this->session->getNode('/cmf/sulu_io/contents')->getIdentifier()); $this->johannes = $this->savePage('simple', ['title' => 'Johannes', 'url' => '/team/johannes'], $this->team->getUuid(), [$this->tag1->getId()]); $this->daniel = $this->savePage('simple', ['title' => 'Daniel', 'url' => '/team/daniel'], $this->team->getUuid()); $this->thomas = $this->savePage('simple', ['title' => 'Thomas', 'url' => '/team/thomas'], $this->team->getUuid()); }
private function upgradeLocale(Webspace $webspace, Localization $localization, OutputInterface $output) { $output->writeln(' > Upgrade Locale: ' . $localization->getLocalization('-')); $contentNode = $this->liveSession->getNode($this->sessionManager->getContentPath($webspace->getKey())); $this->upgradeNode($contentNode, $webspace, $localization, $output); $this->upgradeByParent($contentNode, $webspace, $localization, $output); }
public function testSubRegionSaveTranslation() { // First save some translations $data = array(); $data['topic'] = 'Some interesting subject'; $data['text'] = 'Lorem ipsum...'; $node = $this->getTestNode(); $strategy = new AttributeTranslationStrategy($this->dm); $strategy->saveTranslation($data, $node, $this->metadata, 'en'); // Save translation in another language $data['topic'] = 'Some interesting american subject'; $strategy->saveTranslation($data, $node, $this->metadata, 'en_US'); $this->dm->flush(); // Then test we have what we expect in the content repository $node = $this->session->getNode('/' . $this->testNodeName); $this->assertTrue($node->hasProperty(self::propertyNameForLocale('en', 'topic'))); $this->assertTrue($node->hasProperty(self::propertyNameForLocale('en_US', 'topic'))); $this->assertTrue($node->hasProperty(self::propertyNameForLocale('en', 'text'))); $this->assertTrue($node->hasProperty(self::propertyNameForLocale('en_US', 'text'))); $this->assertFalse($node->hasProperty(self::propertyNameForLocale('en', 'author'))); $this->assertFalse($node->hasProperty(self::propertyNameForLocale('en_US', 'author'))); $this->assertEquals('Some interesting subject', $node->getPropertyValue(self::propertyNameForLocale('en', 'topic'))); $this->assertEquals('Some interesting american subject', $node->getPropertyValue(self::propertyNameForLocale('en_US', 'topic'))); $this->assertEquals('Lorem ipsum...', $node->getPropertyValue(self::propertyNameForLocale('en', 'text'))); $this->assertEquals('Lorem ipsum...', $node->getPropertyValue(self::propertyNameForLocale('en_US', 'text'))); // make sure getLocalesFor works as well. $doc = new Article(); $locales = $strategy->getLocalesFor($doc, $node, $this->metadata); $this->assertEquals(array('en', 'en_US'), $locales); }
/** * Updates the route for the given document after a move or copy. * * @param object $document * @param bool $generateRoutes If set to true a route in the routing tree will also be created */ private function updateRoute($document, $generateRoutes) { $locales = $this->documentInspector->getLocales($document); $webspaceKey = $this->documentInspector->getWebspace($document); $uuid = $this->documentInspector->getUuid($document); $path = $this->documentInspector->getPath($document); $parentUuid = $this->documentInspector->getUuid($this->documentInspector->getParent($document)); $defaultNode = $this->defaultSession->getNode($path); $liveNode = $this->liveSession->getNode($path); $resourceLocatorStrategy = $this->resourceLocatorStrategyPool->getStrategyByWebspaceKey($webspaceKey); foreach ($locales as $locale) { $localizedDocument = $this->documentManager->find($uuid, $locale); if ($localizedDocument->getRedirectType() !== RedirectType::NONE) { continue; } $resourceSegmentPropertyName = $this->encoder->localizedSystemName($this->getResourceSegmentProperty($localizedDocument)->getName(), $locale); $this->updateResourceSegmentProperty($defaultNode, $resourceSegmentPropertyName, $parentUuid, $webspaceKey, $locale); if ($liveNode->hasProperty($resourceSegmentPropertyName)) { $this->updateResourceSegmentProperty($liveNode, $resourceSegmentPropertyName, $parentUuid, $webspaceKey, $locale); // if the method is called with the generateRoutes flag it will create a new route // this happens on a move, but not on copy, because copy results in a draft page without url if ($generateRoutes) { $localizedDocument->setResourceSegment($liveNode->getPropertyValue($resourceSegmentPropertyName)); $resourceLocatorStrategy->save($localizedDocument, null); $localizedDocument->setResourceSegment($defaultNode->getPropertyValue($resourceSegmentPropertyName)); } } } }
/** * {@inheritDoc} */ public function getNodeForDocument($document) { if (!is_object($document)) { throw new InvalidArgumentException('Parameter $document needs to be an object, ' . gettype($document) . ' given'); } $path = $this->unitOfWork->getDocumentId($document); return $this->session->getNode($path); }
/** * Let the visitor visit the ancestors from root node according to mapper * down to the parent of the node identified by url * * @param string $url the url (without eventual prefix from routing config) * @param ItemVisitorInterface $visitor the visitor to look at the nodes */ public function visitAncestors($url, ItemVisitorInterface $visitor) { $node = $this->session->getNode($this->mapper->getStorageId($url)); $i = $this->rootnode->getDepth(); while (($ancestor = $node->getAncestor($i++)) != $node) { $ancestor->accept($visitor); } }
public function testRemove() { $this->property->expects($this->any())->method('getName')->will($this->returnValue('i18n:de-hotels')); $pageNode = $this->session->getNode('/cmf/sulu_io/contents/hotels'); $this->contentType->remove($pageNode, $this->property, 'sulu_io', 'de', null); $this->session->save(); $this->assertFalse($pageNode->hasProperty('i18n:de-hotels')); }
/** * Refresh the given document by querying the PHPCR to get the current state. * * @param object $document * @return object Document instance */ public function refresh($document) { $this->errorIfClosed(); $this->session->refresh(true); $node = $this->session->getNode($this->unitOfWork->getDocumentId($document)); $hints = array('refresh' => true); return $this->unitOfWork->createDocument(get_class($document), $node, $hints); }
private function handleSession(SessionInterface $session, $fileName) { if ($session->getRootNode()->hasNode('cmf')) { $session->getNode('/cmf')->remove(); $session->save(); } $session->importXML('/', $fileName, ImportUUIDBehaviorInterface::IMPORT_UUID_COLLISION_THROW); $session->save(); }
/** * Remove a PHPCR node under the root node * * @param string $name The name of the node to remove * * @return void */ protected function removeTestNode($name) { $root = $this->session->getNode('/'); if ($root->hasNode($name)) { $root->getNode($name)->remove(); $this->session->save(); $this->dm->clear(); } }
/** * {@inheritDoc} */ public function match(EventInterface $event) { if (!$event->getPath()) { // Some events (like PERSIST) don't have a path return false; } // An event might have been raised for a node that does not exist anymore if (!$this->session->nodeExists($event->getPath())) { return false; } $node = $this->session->getNode($event->getPath()); foreach ($this->nodeTypes as $type) { if ($node->isNodeType($type)) { return true; } } return false; }
/** * Refresh the given document by querying the PHPCR to get the current state. * * @param object $document * @return object Document instance */ public function refresh($document) { if (!is_object($document)) { throw new \InvalidArgumentException(gettype($document)); } $this->errorIfClosed(); $this->session->refresh(true); $node = $this->session->getNode($this->unitOfWork->getDocumentId($document)); $hints = array('refresh' => true); return $this->unitOfWork->createDocument(get_class($document), $node, $hints); }
public function testFindByUUID() { $this->doc->topic = 'Un autre sujet'; $this->doc->locale = 'fr'; $this->dm->persist($this->doc); $this->dm->flush(); $node = $this->session->getNode('/functional/' . $this->testNodeName); $node->addMixin('mix:referenceable'); $this->session->save(); $this->document = $this->dm->findTranslation($this->class, $node->getIdentifier(), 'fr'); $this->assertInstanceOf($this->class, $this->document); }
/** * {@inheritdoc} */ public function build() { foreach ($this->webspaceManager->getWebspaceCollection() as $webspace) { $contentPath = $this->sessionManager->getContentPath($webspace->getKey()); $this->context->getOutput()->writeln('Default workspace'); $this->traverse($this->defaultSession->getNode($contentPath)); $this->context->getOutput()->writeln(''); $this->context->getOutput()->writeln('Live workspace'); $this->traverse($this->liveSession->getNode($contentPath)); } $this->defaultSession->save(); $this->liveSession->save(); }
private function getNode($path) { $resolvedPath = $this->resolvePath($path); try { $node = $this->session->getNode($resolvedPath); } catch (\PHPCR\PathNotFoundException $e) { throw new ResourceNotFoundException(sprintf('No PHPCR node could be found at "%s"', $resolvedPath), null, $e); } if (null === $node) { throw new \RuntimeException('Session did not return a node or throw an exception'); } return $node; }
/** * Sets the workflow properties on the given document. * * @param WorkflowStageBehavior $document * @param DocumentAccessor $accessor * @param string $workflowStage * @param string $locale * @param string $live * * @throws \Sulu\Component\DocumentManager\Exception\DocumentManagerException */ private function setWorkflowStage(WorkflowStageBehavior $document, DocumentAccessor $accessor, $workflowStage, $locale, $live) { $path = $this->documentInspector->getPath($document); $document->setWorkflowStage($workflowStage); $updatePublished = !$document->getPublished() && $workflowStage === WorkflowStage::PUBLISHED; if ($updatePublished) { $accessor->set(self::PUBLISHED_FIELD, new \DateTime()); } $defaultNode = $this->defaultSession->getNode($path); $this->setWorkflowStageOnNode($defaultNode, $locale, $workflowStage, $updatePublished); if ($live) { $liveNode = $this->liveSession->getNode($path); $this->setWorkflowStageOnNode($liveNode, $locale, $workflowStage, $updatePublished); } }
/** * Reorder $moved (child of $parent) before or after $target * * @param string $parent the id of the parent * @param string $moved the id of the child being moved * @param string $target the id of the target node * @param bool $before insert before or after the target * * @return void */ public function reorder($parent, $moved, $target, $before) { $parentNode = $this->session->getNode($parent); $targetName = PathHelper::getNodeName($target); if (!$before) { $nodesIterator = $parentNode->getNodes(); $nodesIterator->rewind(); while ($nodesIterator->valid()) { if ($nodesIterator->key() == $targetName) { break; } $nodesIterator->next(); } $targetName = null; if ($nodesIterator->valid()) { $nodesIterator->next(); if ($nodesIterator->valid()) { $targetName = $nodesIterator->key(); } } } $parentNode->orderBefore(PathHelper::getNodeName($moved), $targetName); $this->session->save(); }
/** * {@inheritDoc} * * @api */ public function unlock($absPath) { if (!$this->session->nodeExists($absPath)) { throw new PathNotFoundException("Unable to unlock unexisting node '{$absPath}'"); } if (!array_key_exists($absPath, $this->locks)) { throw new LockException("Unable to find an active lock for the node '{$absPath}'"); } $node = $this->session->getNode($absPath); $state = $node->getState(); if ($state === Item::STATE_NEW || $state === Item::STATE_MODIFIED) { throw new InvalidItemStateException("Cannot unlock the non-clean node '{$absPath}': current state = {$state}"); } $this->transport->unlock($absPath, $this->locks[$absPath]->getLockToken()); $this->locks[$absPath]->setIsLive(false); }
public function testDeleteByRef() { $referrerTestObj = new ReferrerTestObj(); $referrerRefTestObj = new ReferrerRefTestObj(); $referrerTestObj->id = "/functional/referrerTestObj"; $referrerTestObj->name = 'referrer'; $referrerRefTestObj->id = "/functional/referrerRefTestObj"; $referrerTestObj->reference = $referrerRefTestObj; $this->dm->persist($referrerTestObj); $this->dm->flush(); $this->dm->clear(); $reference = $this->dm->find(null, "/functional/referrerRefTestObj"); $this->dm->remove($reference->referrers[0]); $this->dm->flush(); $this->dm->clear(); $this->assertCount(0, $this->dm->find(null, "/functional/referrerRefTestObj")->referrers); $this->assertFalse($this->session->getNode("/functional")->hasNode("referrerTestObj")); }
/** * Return the position of the node within the set of its siblings. * * @return int */ private function getNodePosition($node) { $path = $node->getPath(); $position = null; $parent = $this->session->getNode(PathHelper::getParentPath($path)); $nodes = $parent->getNodes(); $index = 0; foreach ($nodes as $node) { if ($node->getPath() === $path) { $position = $index; break; } ++$index; } if (null === $position) { throw new \RuntimeException(sprintf('Could not find node "%s" as a child of its parent', $path)); } return $position; }
private function migrateHome(SessionInterface $session, $from, $to, $referenceWebspace) { $webspaceManager = $this->container->get('sulu_core.webspace.webspace_manager'); $pathRegistry = $this->container->get('sulu_document_manager.path_segment_registry'); $webspaces = $webspaceManager->getWebspaceCollection(); foreach ($webspaces as $webspace) { $webspacePath = sprintf('/%s/%s', $pathRegistry->getPathSegment('base'), $webspace->getKey()); $homeNodeName = $pathRegistry->getPathSegment('content'); $webspace = $session->getNode($webspacePath); if ($referenceWebspace) { $webspace->addMixin('mix:referenceable'); } else { $webspace->removeMixin('mix:referenceable'); } $homeNode = $webspace->getNode($homeNodeName); $tmpNode = $session->getRootNode()->addNode('/tmp'); $tmpNode->addMixin('mix:referenceable'); $session->save(); $homeNodeReferences = $homeNode->getReferences(); $homeNodeReferenceValues = []; foreach ($homeNodeReferences as $homeNodeReference) { /* @var Property $homeNodeReference */ $homeNodeReferenceValues[$homeNodeReference->getPath()] = $homeNodeReference->getValue(); $homeNodeReference->setValue($tmpNode); } $session->save(); $homeNode->removeMixin($from); $session->save(); $homeNode->addMixin($to); $session->save(); foreach ($homeNodeReferences as $homeNodeReference) { $homeNodeReference->setValue($homeNodeReferenceValues[$homeNodeReference->getPath()], PropertyType::REFERENCE); } $session->save(); $tmpNode->remove(); } }
public function testManyCascadeWithParentDelete() { $refManyTestObjForCascade = new RefManyWithParentTestObjForCascade(); $refManyTestObjForCascade->id = "/functional/refManyWithParentTestObjForCascade"; $references = array(); for ($i = 0; $i < 3; $i++) { $newRefCascadeManyTestObj = new ParentTestObj(); $newRefCascadeManyTestObj->nodename = "ref{$i}"; $newRefCascadeManyTestObj->name = "refCascadeWithParentManyTestObj{$i}"; $references[] = $newRefCascadeManyTestObj; } $refManyTestObjForCascade->setReferences($references); $this->dm->persist($refManyTestObjForCascade); $this->dm->flush(); $this->dm->clear(); $this->assertTrue($this->session->getNode("/functional")->hasNode("refManyWithParentTestObjForCascade")); for ($i = 0; $i < 3; $i++) { $this->assertTrue($this->session->getNode("/functional/refManyWithParentTestObjForCascade")->hasNode("ref{$i}")); } $referrer = $this->dm->find($this->referrerManyWithParentForCascadeType, '/functional/refManyWithParentTestObjForCascade'); $this->dm->remove($referrer); $this->dm->flush(); $this->assertFalse($this->session->getNode("/functional")->hasNode("refManyWithParentTestObjForCascade")); }
/** * Produce the following entries at the end of the event journal:. * * PROPERTY_ADDED /child/jcr:primaryType * NODE_ADDED /child * PERSIST * PROPERTY_ADDED /child/prop * PERSIST * PROPERTY_CHANGED /child/prop * PERSIST * PROPERTY_REMOVED /child/prop * PERSIST * NODE_REMOVED /child * PERSIST * * WARNING: * If you change the events (or the order of events) produced here, you * will have to adapt self::expectEvents so that it checks for the correct * events. * * @param $session */ protected function produceEvents(SessionInterface $session) { $parent = $session->getNode($this->nodePath); // Will cause a PROPERTY_ADDED + a NODE_ADDED events $node = $parent->addNode('child'); // Will cause a PERSIST event $session->save(); // Will case a PROPERTY_ADDED event $prop = $node->setProperty('prop', 'value'); // Will cause a PERSIST event $session->save(); // Will cause a PROPERTY_CHANGED event $prop->setValue('something else'); // Will cause a PERSIST event $session->save(); // Will cause a PROPERTY_REMOVED event $prop->remove(); // Will cause a PERSIST event $session->save(); // Will cause a NODE_REMOVED + NODE_ADDED + NODE_MOVED events $session->move($node->getPath(), $this->nodePath . '/moved'); // Will cause a PERSIST event $session->save(); // Will cause a NODE_REMOVED event $node->remove(); // Will cause a PERSIST event $session->save(); }
/** * @see \PHPCR\SessionInterface::getNode */ public function getNode($absPath, $depthHint = -1) { $node = $this->session->getNode($absPath, $depthHint); return new Node($node); }
/** * changes path node to history node. * * @param NodeInterface $node * @param SessionInterface $session * @param string $absSrcPath * @param string $absDestPath */ private function changePathToHistory(NodeInterface $node, SessionInterface $session, $absSrcPath, $absDestPath) { // get new path node $relPath = str_replace($absSrcPath, '', $node->getPath()); $newPath = PathHelper::normalizePath($absDestPath . $relPath); $newPathNode = $session->getNode($newPath); // set history to true and set content to new path $node->setProperty('sulu:content', $newPathNode); $node->setProperty('sulu:history', true); // get referenced history /** @var PropertyInterface $property */ foreach ($node->getReferences('sulu:content') as $property) { $property->getParent()->setProperty('sulu:content', $newPathNode); } }
/** * @param SessionInterface $session * @param QueryResultInterface $rows * * @return array */ protected function buildSearchResults(SessionInterface $session, QueryResultInterface $rows) { $searchResults = array(); /** @var $row RowInterface */ foreach ($rows as $row) { if (!$row->getValue('class')) { $parent = $session->getNode(PathHelper::getParentPath($row->getPath())); $contentId = $parent->getIdentifier(); $node = $parent; } else { $contentId = $row->getValue('uuid') ?: $row->getPath(); $node = $row->getNode(); } $url = $this->mapUrl($session, $node); if (false === $url) { continue; } $searchResults[$contentId] = array('url' => $url, 'title' => $row->getValue($this->searchFields['title']), 'summary' => $this->buildSummary($row)); } return $searchResults; }