Example #1
0
 public function setUp()
 {
     $this->dm = $this->createDocumentManager(array(__DIR__));
     $repository = $this->dm->getPhpcrSession()->getRepository();
     if (!$repository->getDescriptor('node.type.management.orderable.child.nodes.supported')) {
         $this->markTestSkipped('PHPCR repository doesn\'t support orderable child nodes');
     }
     $this->node = $this->resetFunctionalNode($this->dm);
     $parent = $this->dm->find(null, $this->node->getPath());
     $node1 = new Generic();
     $node1->setParentDocument($parent);
     $node1->setNodename('source');
     $this->dm->persist($node1);
     $this->childrenNames = array('first', 'second', 'third', 'fourth');
     foreach ($this->childrenNames as $childName) {
         $child = new Generic();
         $child->setNodename($childName);
         $child->setParentDocument($node1);
         $this->dm->persist($child);
     }
     $node2 = new Generic();
     $node2->setNodename('target');
     $node2->setParentDocument($parent);
     $this->dm->persist($node2);
     $this->dm->flush();
     $this->dm->clear();
 }
 public function loadFixtures()
 {
     $contentMapperRequest = ContentMapperRequest::create()->setType(Structure::TYPE_SNIPPET)->setTemplateKey('animal')->setLocale('en')->setUserId(1)->setData(['title' => 'ElePHPant'])->setState(StructureInterface::STATE_PUBLISHED);
     $this->snippet1 = $this->contentMapper->saveRequest($contentMapperRequest);
     $contentMapperRequest = ContentMapperRequest::create()->setType(Structure::TYPE_SNIPPET)->setTemplateKey('animal')->setLocale('de')->setUserId(1)->setData(['title' => 'Penguin'])->setState(StructureInterface::STATE_PUBLISHED);
     $this->snippet2 = $this->contentMapper->saveRequest($contentMapperRequest);
     $this->snippet1Node = $this->session->getNodeByIdentifier($this->snippet1->getUuid());
     $this->snippet1OriginalPath = $this->snippet1Node->getPath();
     $contentMapperRequest = ContentMapperRequest::create()->setUuid($this->snippet1->getUuid())->setType(Structure::TYPE_SNIPPET)->setTemplateKey('animal')->setLocale('de')->setUserId(1)->setData(['title' => 'English ElePHPant'])->setState(StructureInterface::STATE_PUBLISHED);
     $this->contentMapper->saveRequest($contentMapperRequest);
     $contentMapperRequest = ContentMapperRequest::create()->setType(Structure::TYPE_SNIPPET)->setTemplateKey('animal')->setLocale('en')->setUserId(1)->setData(['title' => 'Some other animal'])->setState(StructureInterface::STATE_PUBLISHED);
     $this->contentMapper->saveRequest($contentMapperRequest);
 }
 protected function toJsonLD(NodeInterface $node)
 {
     $data = $node->getPropertiesValues(null, false);
     $data['@'] = $node->getPath();
     $data['a'] = $node->getPrimaryNodeType();
     return $data;
 }
 /**
  * Traverse the node
  *
  * @param NodeInterface|null $node  The node to traverse, if it exists yet
  * @param array $segments  The element => token stack
  * @param array $result  The result
  *
  * @return null
  */
 private function traverse(array $segments, &$result = array(), $node = null)
 {
     $path = array();
     if (null !== $node) {
         $path = explode('/', substr($node->getPath(), 1));
     }
     do {
         list($element, $bitmask) = array_shift($segments);
         if ($bitmask & SelectorParser::T_STATIC) {
             $path[] = $element;
             if ($bitmask & SelectorParser::T_LAST) {
                 if ($node = $this->getNode($path)) {
                     $result[] = $node;
                     break;
                 }
             }
         }
         if ($bitmask & SelectorParser::T_PATTERN) {
             if (null === ($parentNode = $this->getNode($path))) {
                 return;
             }
             $children = $this->getChildren($parentNode, $element);
             foreach ($children as $child) {
                 if ($bitmask & SelectorParser::T_LAST) {
                     $result[] = $child;
                 } else {
                     $this->traverse($segments, $result, $child);
                 }
             }
             return;
         }
     } while ($segments);
 }
    /**
     * Gets a relative filesystem path based on the repository path, AND
     * creates the file on the filesystem if it's in the repository
     * and not yet on the filesystem.
     * The repository path points to a nt-resource node, whose title
     * should be the filename, and which has a child+property
     * jcr:content/jcr:data where the file data is stored.
     *
     * @param string $path path to the nt-resource node.
     * @return string with a path to the file, relative to the web directory.
     */
    public function getUrl(NodeInterface $node)
    {

        $hasData = false;
        if ($node->hasNode('jcr:content')) {
            $contentNode = $node->getNode('jcr:content');
            if ($contentNode->hasProperty('jcr:data')) {
                $hasData = true;
            }
        }
        if (!$hasData) {
            //TODO: notfound exception is not appropriate ... how to best do this?
            //throw new NotFoundHttpException('no picture found at ' . $node->getPath());
            return 'notfound';
        }

        $path = $node->getPath();
        $relativePath = $this->pathMapper->getUrl($path);
        $fullPath = $this->fileBasePath . $relativePath . $this->getExtension($contentNode);

        if (!file_exists($fullPath)) {
            try {
                $this->saveData($contentNode, $fullPath);
            } catch (Imagine\Exception\Exception $e) {
                //TODO: notfound exception is not appropriate ... how to best do this?
                //throw new NotFoundHttpException('image save to filesystem failed: ' . $e->getMessage());
                return 'notfound';
            }
        }

        return $this->webRelativePath . $relativePath . $this->getExtension($contentNode);
    }
 /**
  * Gets a relative filesystem path based on the repository path, AND
  * creates the file on the filesystem if it's in the repository
  * and not yet on the filesystem.
  * The repository path points to a nt-resource node, whose title
  * should be the filename, and which has a child+property
  * jcr:content/jcr:data where the file data is stored.
  *
  * @param string $path path to the nt-resource node.
  * @return string with a path to the file, relative to the web directory.
  */
 public function getUrl(NodeInterface $node)
 {
     $hasData = false;
     if ($node->hasNode('jcr:content')) {
         $contentNode = $node->getNode('jcr:content');
         if ($contentNode->hasProperty('jcr:data')) {
             $hasData = true;
         }
     }
     if (!$hasData) {
         //TODO: notfound exception is not appropriate ... how to best do this?
         //throw new NotFoundHttpException('no picture found at ' . $node->getPath());
         return 'notfound';
     }
     $path = $node->getPath();
     $relativePath = $this->pathMapper->getUrl($path);
     $extension = $this->getExtension($contentNode);
     $fullPath = $this->fileBasePath . '/' . $relativePath . $extension;
     if (!file_exists($fullPath)) {
         if (!$this->saveData($contentNode, $fullPath)) {
             throw new FileException('failed to save data to file: ' . $fullPath);
         }
     }
     return $this->webRelativePath . '/' . $relativePath . $extension;
 }
 /**
  * Transform a node into a path.
  *
  * @param \PHPCR\NodeInterface|null $node
  *
  * @return string|null the path to the node or null if $node is null
  *
  * @throws UnexpectedTypeException if given value is not a \PHPCR\NodeInterface
  */
 public function transform($node)
 {
     if (null === $node) {
         return;
     }
     if (!$node instanceof NodeInterface) {
         throw new UnexpectedTypeException($node, 'PHPCR\\NodeInterface');
     }
     return $node->getPath();
 }
Example #8
0
 public function it_should_provide_a_method_to_determine_if_a_node_is_versionable(NodeInterface $nodeVersionable, NodeInterface $nodeNotVersionable, NodeTypeInterface $mixin1, NodeTypeInterface $mixin2)
 {
     $nodeVersionable->getMixinNodeTypes()->willReturn(array($mixin1, $mixin2));
     $nodeNotVersionable->getMixinNodeTypes()->willReturn(array($mixin2));
     $nodeNotVersionable->getPath()->willReturn('foobar');
     $mixin1->getName()->willReturn('mix:versionable');
     $this->assertNodeIsVersionable($nodeVersionable)->shouldReturn(null);
     try {
         $this->assertNodeIsVersionable($nodeNotVersionable);
     } catch (\OutOfBoundsException $e) {
     }
 }
 public function testFlushNullableFieldNotSetUpdate()
 {
     $doc = new Article();
     $doc->id = $this->node->getPath() . '/flush';
     $doc->topic = 'title';
     $doc->text = 'text';
     $doc->locale = 'en';
     $this->dm->persist($doc);
     $this->dm->flush();
     $this->setExpectedException('Doctrine\\ODM\\PHPCR\\PHPCRException');
     $doc->topic = null;
     $this->dm->flush();
 }
 /**
  * {@inheritDoc}
  */
 public function getClassName(DocumentManagerInterface $dm, NodeInterface $node, $className = null)
 {
     $className = $this->expandClassName($dm, $className);
     if ($node->hasProperty('phpcr:class')) {
         $nodeClassName = $node->getProperty('phpcr:class')->getString();
         if (!empty($className) && $nodeClassName !== $className && !is_subclass_of($nodeClassName, $className)) {
             throw ClassMismatchException::incompatibleClasses($node->getPath(), $nodeClassName, $className);
         }
         $className = $nodeClassName;
     }
     // default to the built in generic document class
     if (empty($className)) {
         $className = 'Doctrine\\ODM\\PHPCR\\Document\\Generic';
     }
     return $className;
 }
 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();
 }
 /**
  *
  * Returns an array representation of a PHPCR node
  *
  * @param string $name
  * @param \PHPCR\NodeInterface $node
  *
  * @return array
  */
 private function nodeToArray($name, $node)
 {
     $has_children = $node->hasNodes();
     return array('data' => $name, 'attr' => array('id' => $node->getPath(), 'url_safe_id' => substr($node->getPath(), 1), 'rel' => 'node'), 'state' => $has_children ? 'closed' : null);
 }
Example #13
0
 /**
  * Load/hydrate a shalow structure with the given node.
  * Shallow structures do not have content properties / extensions
  * hydrated.
  *
  * @param NodeInterface $node
  * @param string        $localization
  * @param string        $webspaceKey
  *
  * @return StructureInterface
  */
 public function loadShallowStructureByNode(NodeInterface $contentNode, $localization, $webspaceKey)
 {
     $document = $this->documentManager->find($contentNode->getPath(), $localization);
     return $this->documentToStructure($document);
 }
Example #14
0
 /**
  * This method will either let the transport filter if that is possible or
  * forward to getNodes and return the names of the nodes found there.,
  *
  * @param NodeInterface $node
  * @param string|array  $nameFilter
  * @param string|array  $typeFilter
  *
  * @return ArrayIterator
  */
 public function filterChildNodeNamesByType(NodeInterface $node, $nameFilter, $typeFilter)
 {
     if ($this->transport instanceof NodeTypeFilterInterface) {
         return $this->transport->filterChildNodeNamesByType($node->getPath(), $node->getNodeNames($nameFilter), $typeFilter);
     }
     // fallback: get the actual nodes and let that filter. this is expensive.
     return new ArrayIterator(array_keys($node->getNodes($nameFilter, $typeFilter)->getArrayCopy()));
 }
Example #15
0
 /**
  * Return either the next or previous sibling of the given node
  * according to the $previous flag.
  *
  * @param NodeInterface $node
  * @param bool          $previous
  *
  * @return NodeInterface|null
  *
  * @throws \RuntimeException
  */
 private function getSiblingNode(NodeInterface $node, $previous = false)
 {
     $parentNode = $node->getParent();
     $children = $parentNode->getNodes();
     $previousNode = null;
     while ($child = current($children)) {
         if ($child->getPath() === $node->getPath()) {
             return $previous ? $previousNode : next($children);
         }
         $previousNode = $child;
         next($children);
     }
     throw new \RuntimeException(sprintf('Could not find node with path "%s" as a child of "%s". This should not happen', $node->getPath(), $parentNode->getPath()));
 }
 public function testGetPath()
 {
     $path = $this->deepnode->getPath();
     $this->assertEquals('/tests_general_base/multiValueProperty/deepnode', $path);
 }
Example #17
0
 /**
  * Recursively output node and all its children into the file in the system
  * view format
  *
  * @param NodeInterface $node the node to output
  * @param resource $stream The stream resource (i.e. aquired with fopen) to
  *      which the XML serialization of the subgraph will be output. Must
  *      support the fwrite method.
  * @param boolean $skipBinary A boolean governing whether binary properties
  *      are to be serialized.
  * @param boolean $noRecurse A boolean governing whether the subgraph at
  *      absPath is to be recursed.
  * @param boolean $root Whether this is the root node of the resulting
  *      document, meaning the namespace declarations have to be included in
  *      it.
  *
  * @return void
  */
 private static function exportSystemViewRecursive(NodeInterface $node, NamespaceRegistryInterface $ns, $stream, $skipBinary, $noRecurse, $root = false)
 {
     fwrite($stream, '<sv:node');
     if ($root) {
         self::exportNamespaceDeclarations($ns, $stream);
     }
     fwrite($stream, ' sv:name="' . ($node->getPath() == '/' ? 'jcr:root' : htmlspecialchars($node->getName())) . '">');
     // the order MUST be primary type, then mixins, if any, then jcr:uuid if its a referenceable node
     fwrite($stream, '<sv:property sv:name="jcr:primaryType" sv:type="Name"><sv:value>' . htmlspecialchars($node->getPropertyValue('jcr:primaryType')) . '</sv:value></sv:property>');
     if ($node->hasProperty('jcr:mixinTypes')) {
         fwrite($stream, '<sv:property sv:name="jcr:mixinTypes" sv:type="Name" sv:multiple="true">');
         foreach ($node->getPropertyValue('jcr:mixinTypes') as $type) {
             fwrite($stream, '<sv:value>' . htmlspecialchars($type) . '</sv:value>');
         }
         fwrite($stream, '</sv:property>');
     }
     if ($node->isNodeType('mix:referenceable')) {
         fwrite($stream, '<sv:property sv:name="jcr:uuid" sv:type="String"><sv:value>' . $node->getIdentifier() . '</sv:value></sv:property>');
     }
     foreach ($node->getProperties() as $name => $property) {
         if ($name == 'jcr:primaryType' || $name == 'jcr:mixinTypes' || $name == 'jcr:uuid') {
             // explicitly handled before
             continue;
         }
         if (PropertyType::BINARY == $property->getType() && $skipBinary) {
             // do not output binary data in the xml
             continue;
         }
         fwrite($stream, '<sv:property sv:name="' . htmlentities($name) . '" sv:type="' . PropertyType::nameFromValue($property->getType()) . '"' . ($property->isMultiple() ? ' sv:multiple="true"' : '') . '>');
         $values = $property->isMultiple() ? $property->getString() : array($property->getString());
         foreach ($values as $value) {
             if (PropertyType::BINARY == $property->getType()) {
                 $val = base64_encode($value);
             } else {
                 $val = htmlspecialchars($value);
                 //TODO: can we still have invalid characters after this? if so base64 and property, xsi:type="xsd:base64Binary"
             }
             fwrite($stream, "<sv:value>{$val}</sv:value>");
         }
         fwrite($stream, "</sv:property>");
     }
     if (!$noRecurse) {
         foreach ($node as $child) {
             if (!($child->getDepth() == 1 && NodeHelper::isSystemItem($child))) {
                 self::exportSystemViewRecursive($child, $ns, $stream, $skipBinary, $noRecurse);
             }
         }
     }
     fwrite($stream, '</sv:node>');
 }
 /**
  * Ensure that the document is not already registered and that the node
  * has a UUID.
  *
  * @param object $document
  * @param NodeInterface $node
  * @param string $oid
  * @param string $uuid
  *
  * @throws DocumentManagerException
  */
 private function validateDocumentRegistration($document, NodeInterface $node, $oid, $uuid)
 {
     if (null === $uuid) {
         throw new DocumentManagerException(sprintf('Node "%s" of type "%s" has no UUID. Only referencable nodes can be registered by the document manager', $node->getPath(), $node->getPrimaryNodeType()->getName()));
     }
     if (isset($this->nodeMap[$uuid])) {
         $registeredDocument = $this->nodeDocumentMap[$uuid];
         throw new \RuntimeException(sprintf('Document "%s" (%s) is already registered for node "%s" (%s) when trying to register document "%s" (%s)', spl_object_hash($registeredDocument), get_class($registeredDocument), $uuid, $node->getPath(), $oid, get_class($document)));
     }
 }
 /**
  * Renders a path of a node
  *
  * @param \PHPCR\NodeInterface $node
  * @return string Node path
  */
 public function renderNodePath(NodeInterface $node)
 {
     return $node->getPath();
 }
Example #20
0
 /**
  * Validate this node with the nodetype and generate not yet existing
  * autogenerated properties as necessary.
  *
  * @param NodeInterface $node
  * @param NodeType      $nodeTypeDefinition
  *
  * @return AddNodeOperation[] Additional operations to handle autocreated nodes.
  *
  * @throws \InvalidArgumentException
  * @throws RepositoryException
  * @throws ItemExistsException
  * @throws LockException
  * @throws ConstraintViolationException
  * @throws PathNotFoundException
  * @throws VersionException
  * @throws ValueFormatException
  */
 private function processNodeWithType(NodeInterface $node, NodeType $nodeTypeDefinition)
 {
     $additionalOperations = array();
     foreach ($nodeTypeDefinition->getDeclaredChildNodeDefinitions() as $childDef) {
         /* @var $childDef NodeDefinitionInterface */
         if (!$node->hasNode($childDef->getName())) {
             if ('*' === $childDef->getName()) {
                 continue;
             }
             if ($childDef->isMandatory() && !$childDef->isAutoCreated()) {
                 throw new RepositoryException(sprintf('Child "%s" is mandatory, but is not present while saving "%s" at path "%s"', $childDef->getName(), $nodeTypeDefinition->getName(), $node->getPath()));
             }
             if ($childDef->isAutoCreated()) {
                 $requiredPrimaryTypeNames = $childDef->getRequiredPrimaryTypeNames();
                 $primaryType = count($requiredPrimaryTypeNames) ? current($requiredPrimaryTypeNames) : null;
                 $newNode = $node->addNode($childDef->getName(), $primaryType);
                 $absPath = $node->getPath() . '/' . $childDef->getName();
                 $operation = new AddNodeOperation($absPath, $newNode);
                 $additionalOperations[] = $operation;
             }
         }
     }
     foreach ($nodeTypeDefinition->getDeclaredPropertyDefinitions() as $propertyDef) {
         /* @var $propertyDef PropertyDefinitionInterface */
         if ('*' === $propertyDef->getName()) {
             continue;
         }
         if (!$node->hasProperty($propertyDef->getName())) {
             if ($propertyDef->isMandatory() && !$propertyDef->isAutoCreated()) {
                 throw new RepositoryException(sprintf('Property "%s" is mandatory, but is not present while saving "%s" at "%s"', $propertyDef->getName(), $nodeTypeDefinition->getName(), $node->getPath()));
             }
             if ($propertyDef->isAutoCreated()) {
                 switch ($propertyDef->getName()) {
                     case 'jcr:uuid':
                         $value = UUIDHelper::generateUUID();
                         break;
                     case 'jcr:createdBy':
                     case 'jcr:lastModifiedBy':
                         $value = $this->userId;
                         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(sprintf('No default value for autocreated property "%s" at "%s"', $propertyDef->getName(), $node->getPath()));
                         }
                 }
                 $node->setProperty($propertyDef->getName(), $value, $propertyDef->getRequiredType());
             }
         } elseif ($propertyDef->isAutoCreated()) {
             $prop = $node->getProperty($propertyDef->getName());
             if (!$prop->isModified() && !$prop->isNew()) {
                 switch ($propertyDef->getName()) {
                     case 'jcr:lastModified':
                         if ($this->autoLastModified) {
                             $prop->setValue(new \DateTime());
                         }
                         break;
                     case 'jcr:lastModifiedBy':
                         if ($this->autoLastModified) {
                             $prop->setValue($this->userId);
                         }
                         break;
                     case 'jcr:etag':
                         // TODO: update etag if needed
                         break;
                 }
             }
         }
     }
     foreach ($nodeTypeDefinition->getDeclaredSupertypes() as $superType) {
         $this->processNodeWithType($node, $superType);
     }
     foreach ($node->getProperties() as $property) {
         $this->assertValidProperty($property);
     }
     return $additionalOperations;
 }
Example #21
0
 /**
  * Cleanup specific node and his children.
  *
  * @param NodeInterface $node
  * @param string        $rootPath
  * @param bool          $dryRun
  */
 private function cleanup(OutputInterface $output, NodeInterface $node, $rootPath, $dryRun)
 {
     foreach ($node->getNodes() as $childNode) {
         $this->cleanup($output, $childNode, $rootPath, $dryRun);
     }
     $path = ltrim(str_replace($rootPath, '', $node->getPath()), '/');
     if (!$node->getPropertyValueWithDefault('sulu:history', false)) {
         $output->writeln('<info>Processing aborted: </info>/' . $path . ' <comment>(no history url)</comment>');
         return;
     }
     if ($dryRun === false) {
         $node->remove();
     }
     $output->writeln('<info>Processing: </info>/' . $path);
 }
Example #22
0
 /**
  * {@inheritdoc}
  */
 public function getPath()
 {
     return $this->node->getPath();
 }
Example #23
0
 /**
  * Get the existing document or proxy or create a new one for this PHPCR Node
  *
  * @param NodeInterface $node
  * @param string        $locale
  *
  * @return object
  */
 public function getOrCreateProxyFromNode(NodeInterface $node, $locale = null)
 {
     $targetId = $node->getPath();
     $className = $this->documentClassMapper->getClassName($this->dm, $node);
     return $this->getOrCreateProxy($targetId, $className, $locale);
 }
Example #24
0
 /**
  * Helper method for importing to add a node with the proper uuid behavior
  *
  * @param \PHPCR\NodeInterface $parentNode   the node to add this node to
  * @param string               $nodename     the node name to use
  * @param string               $type         the primary type name to use
  * @param int                  $uuidBehavior one of the constants of ImportUUIDBehaviorInterface
  *
  * @return NodeInterface the created node
  *
  * @throws \PHPCR\ItemExistsException if IMPORT_UUID_COLLISION_THROW and
  *      duplicate id
  * @throws \PHPCR\NodeType\ConstraintViolationException if behavior is remove or
  *      replace and the node with the uuid is in the parent path.
  */
 private static function addNode(NodeInterface $parentNode, $nodename, $type, $properties, $uuidBehavior)
 {
     $forceReferenceable = false;
     if (isset($properties['jcr:uuid'])) {
         try {
             $existing = $parentNode->getSession()->getNodeByIdentifier($properties['jcr:uuid']['values']);
             switch ($uuidBehavior) {
                 case self::IMPORT_UUID_CREATE_NEW:
                     unset($properties['jcr:uuid']);
                     $forceReferenceable = true;
                     break;
                 case self::IMPORT_UUID_COLLISION_THROW:
                     throw new ItemExistsException('There already is a node with uuid ' . $properties['jcr:uuid']['values'] . ' in this workspace.');
                 case self::IMPORT_UUID_COLLISION_REMOVE_EXISTING:
                 case self::IMPORT_UUID_COLLISION_REPLACE_EXISTING:
                     if (self::IMPORT_UUID_COLLISION_REPLACE_EXISTING == $uuidBehavior && 'jcr:root' == $nodename && $existing->getDepth() == 0) {
                         break;
                     }
                     if (!strncmp($existing->getPath() . '/', $parentNode->getPath() . "/{$nodename}", strlen($existing->getPath() . '/'))) {
                         throw new ConstraintViolationException('Trying to remove/replace parent of the path we are adding to. ' . $existing->getIdentifier() . ' at ' . $existing->getPath());
                     }
                     if (self::IMPORT_UUID_COLLISION_REPLACE_EXISTING == $uuidBehavior) {
                         // replace the found node. spec is not precise: do we keep the name or use the one of existing?
                         $parentNode = $existing->getParent();
                     }
                     $existing->remove();
                     break;
                 default:
                     // @codeCoverageIgnoreStart
                     throw new RepositoryException("Unexpected type {$uuidBehavior}");
                     // @codeCoverageIgnoreEnd
             }
         } catch (\PHPCR\ItemNotFoundException $e) {
             // nothing to do, we can add the node without conflict
         }
     }
     /* we add a jcr:root somewhere in the tree (either create new ids or
      * the root was not referenceable. do not make jackrabbit think it
      * would be the real root node.
      */
     if ('jcr:root' === $nodename && 'rep:root' === $type) {
         $type = 'nt:unstructured';
     }
     if ('jcr:root' == $nodename && isset($existing) && $existing->getDepth() === 0 && self::IMPORT_UUID_COLLISION_REPLACE_EXISTING == $uuidBehavior) {
         // update the root node properties
         // http://www.day.com/specs/jcr/2.0/11_Import.html#11.9%20Importing%20%3CI%3Ejcr:root%3C/I%3E
         NodeHelper::purgeWorkspace($parentNode->getSession());
         $node = $existing;
     } else {
         $node = $parentNode->addNode($nodename, $type);
     }
     foreach ($properties as $name => $info) {
         if ('jcr:primaryType' == $name) {
             // handled in node constructor
         } elseif ('jcr:mixinTypes' == $name) {
             if (is_array($info['values'])) {
                 foreach ($info['values'] as $type) {
                     $node->addMixin($type);
                 }
             } else {
                 $node->addMixin($info['values']);
             }
         } elseif ('jcr:created' == $name || 'jcr:createdBy' == $name) {
             // skip PROTECTED properties. TODO: get the names from node type instead of hardcode
         } elseif ('jcr:uuid' == $name) {
             //avoid to throw an exception when trying to set a UUID when importing from XML
             $node->setProperty($name, $info['values'], $info['type'], false);
         } else {
             $node->setProperty($name, $info['values'], $info['type']);
         }
     }
     if ($forceReferenceable && !$node->isNodeType('mix:referenceable')) {
         $node->addMixin('mix:referenceable');
     }
     return $node;
 }
Example #25
0
 /**
  * Creates every node on the path to the given node. Also uses the same UUIDs for these nodes.
  *
  * @param NodeInterface $node
  */
 private function createNodesWithUuid(NodeInterface $node)
 {
     $path = $node->getPath();
     if ($this->liveSession->itemExists($path)) {
         return;
     }
     $currentDefaultNode = $node->getSession()->getRootNode();
     $currentLiveNode = $this->liveSession->getRootNode();
     $pathSegments = explode('/', ltrim($path, '/'));
     foreach ($pathSegments as $pathSegment) {
         $currentDefaultNode = $currentDefaultNode->getNode($pathSegment);
         if ($currentLiveNode->hasNode($pathSegment)) {
             $currentLiveNode = $currentLiveNode->getNode($pathSegment);
             continue;
         }
         $currentLiveNode = $currentLiveNode->addNode($pathSegment);
         $currentLiveNode->setMixins(['mix:referenceable']);
         $currentLiveNode->setProperty('jcr:uuid', $currentDefaultNode->getIdentifier());
     }
 }
Example #26
0
 /**
  * Gather the parent and all child mappings so they can be fetched in one
  * go.
  *
  * @param ClassMetadata $class  The metadata about the document to know what to do.
  * @param NodeInterface $node   The node to prefetch parent and childs for.
  * @param string|null   $locale The locale to also prefetch the translation
  *      child if applicable.
  *
  * @return array List of absolute paths to nodes that should be prefetched.
  */
 public function collectPrefetchHierarchy(ClassMetadata $class, NodeInterface $node, $locale = null)
 {
     $prefetch = array();
     if ($class->parentMapping && $node->getDepth() > 0) {
         $prefetch[] = PathHelper::getParentPath($node->getPath());
     }
     foreach ($class->childMappings as $fieldName) {
         $childName = $class->mappings[$fieldName]['nodeName'];
         $prefetch[] = PathHelper::absolutizePath($childName, $node->getPath());
     }
     if ($locale && count($prefetch) && 'child' === $class->translator) {
         $prefetch[] = $node->getPath() . '/phpcr_locale:' . $locale;
     }
     return $prefetch;
 }
Example #27
0
 /**
  * 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);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function getDebugMessage()
 {
     return sprintf('n:%s d:%s l:%s', $this->node ? $this->node->getPath() : '<no node>', $this->document ? spl_object_hash($this->document) : '<no document>', $this->locale ?: '<no locale>');
 }