/** * {@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; }
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 testPropertyRead() { $this->property->expects($this->exactly(2))->method('getName')->will($this->returnValue('i18n:de-hotels')); $this->property->expects($this->once())->method('setValue')->will($this->returnCallback(function ($snippets) { foreach ($snippets as $snippet) { $this->assertTrue(UUIDHelper::isUUID($snippet)); } })); $pageNode = $this->session->getNode('/cmf/sulu_io/contents/hotels'); $this->contentType->read($pageNode, $this->property, 'sulu_io', 'de', null); }
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 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())); }
/** * {@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); }
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; }
/** * Normalize the given path or ID to a path. * * @param string $identifier * * @return string */ private function normalizeToPath($identifier) { if (UUIDHelper::isUUID($identifier)) { $identifier = $this->session->getNodeByIdentifier($identifier)->getPath(); } return $identifier; }
/** * 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); }
/** * {@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); }
public function findNodes($patternOrId) { if (true === UUIDHelper::isUUID($patternOrId)) { return $this->getNodeByIdentifier($patternOrId); } $res = $this->finder->find($this->getAbsPath($patternOrId)); return $res; }
/** * {@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; }
/** * Get the nodes identified by the given uuids or absolute paths. * * Note uuids/paths that cannot be found will be ignored * * @param array $identifiers uuid's or absolute paths * @param string $class optional class name for the factory * * @return ArrayIterator of NodeInterface of the specified nodes keyed by their path * * @throws RepositoryException if another error occurs. * * @see Session::getNodes() */ public function getNodes($identifiers, $class = 'Node') { // TODO get paths for UUID's via a single query $paths = array(); foreach ($identifiers as $key => $identifier) { if (UUIDHelper::isUUID($identifier)) { if (empty($this->objectsByUuid[$identifier])) { try { $paths[$key] = $this->transport->getNodePathForIdentifier($identifier); } catch (ItemNotFoundException $e) { // ignore } } else { $paths[$key] = $this->objectsByUuid[$identifier]; } } else { $paths[$key] = $identifier; } } return $this->getNodesByPath($paths, $class); }
/** * {@inheritDoc} * * @api */ public function getNode() { $this->checkState(); $values = $this->isMultiple() ? $this->value : array($this->value); $results = array(); switch ($this->type) { case PropertyType::REFERENCE: $results = $this->objectManager->getNodesByIdentifier($values); $results = $results->getArrayCopy(); if (array_keys($results) != $values) { // @codeCoverageIgnoreStart throw new RepositoryException('Internal Error: Could not find a referenced node. If the referencing node is a frozen version, this can happen, otherwise it would be a bug.'); // @codeCoverageIgnoreEnd } 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); }
/** * 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; }
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())); }
public function testImportXMLDocument() { // TODO: have a node that tests unescaping in the documentview.xml and check self::$staticSharedFixture['ie']->import('11_Import/idnode'); $session = $this->renewSession(); $session->importXML('/', __DIR__ . '/../../fixtures/11_Import/documentview.xml', ImportUUIDBehaviorInterface::IMPORT_UUID_CREATE_NEW); // existing node did not change its uuid $this->assertTrue($session->nodeExists('/container/idExample')); $idExample = $session->getNode('/container/idExample'); $this->assertEquals('842e61c0-09ab-42a9-87c0-308ccc90e6f4', $idExample->getIdentifier()); $this->assertTrue($session->nodeExists('/tests_import')); $this->assertTrue($session->nodeExists('/tests_import/idExample')); $id = $session->getNode('/tests_import/idExample'); $this->assertTrue($id->isNodeType('mix:referenceable')); $this->assertTrue($session->propertyExists('/tests_import/idExample/jcr:content/weakreference_source1/ref1')); $ref = $session->getProperty('/tests_import/idExample/jcr:content/weakreference_source1/ref1'); $this->assertTrue(\PHPCR\Util\UUIDHelper::isUUID($ref->getString())); $session = $this->saveAndRenewSession(); // existing node did not change its uuid $this->assertTrue($session->nodeExists('/container/idExample')); $idExample = $session->getNode('/container/idExample'); $this->assertEquals('842e61c0-09ab-42a9-87c0-308ccc90e6f4', $idExample->getIdentifier()); $this->assertTrue($session->nodeExists('/tests_import')); $this->assertTrue($session->nodeExists('/tests_import/idExample')); $id = $session->getNode('/tests_import/idExample'); $this->assertTrue($id->isNodeType('mix:referenceable')); $this->assertTrue($session->propertyExists('/tests_import/idExample/jcr:content/weakreference_source1/ref1')); $ref = $session->getProperty('/tests_import/idExample/jcr:content/weakreference_source1/ref1'); $this->assertTrue(\PHPCR\Util\UUIDHelper::isUUID($ref->getString())); }
/** * Check if the given uuid is valid. * * @param $uuid * @return bool */ public function isValidUuid($uuid) { return UUIDHelper::isUUID($uuid); }
/** * {@inheritDoc} */ public function findTranslation($className, $id, $locale, $fallback = true) { try { if (UUIDHelper::isUUID($id)) { try { $id = $this->session->getNodeByIdentifier($id)->getPath(); } catch (ItemNotFoundException $e) { return null; } } elseif (strpos($id, '/') !== 0) { $id = '/' . $id; } $document = $this->unitOfWork->getDocumentById($id); if ($document) { $this->unitOfWork->validateClassName($document, $className); $class = $this->getClassMetadata(get_class($document)); $this->unitOfWork->doLoadTranslation($document, $class, $locale, $fallback); return $document; } $node = $this->session->getNode($id); } catch (PathNotFoundException $e) { return null; } $hints = array('locale' => $locale, 'fallback' => $fallback); return $this->unitOfWork->getOrCreateDocument($className, $node, $hints); }
/** * 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); } } }
/** * 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; }