/** * Create an array of common neighbors from the input array * * @param array $data - array of incoming "paths" arrays * * @return void */ private function addCommonNeighborsFromArray(array $data) { $k = array_keys($data); $k = $k[0]; $this->_result[$k] = array(); foreach ($data[$k] as $neighbor => $neighbors) { $this->_result[$k][$neighbor] = array(); foreach ($neighbors as $n) { $this->_result[$k][$neighbor][] = Document::createFromArray($n); } } }
/** * Get the batch part identified by the array key (0...n) or its id (if it was set with nextBatchPartId($id) ) * * @throws ClientException * @return mixed $partId */ public function getProcessedResponse() { $response = $this->getResponse(); switch ($this->_type) { case 'getdocument': $json = $response->getJson(); $options = $this->getCursorOptions(); $options['isNew'] = false; $response = Document::createFromArray($json, $options); break; case 'document': $json = $response->getJson(); if ($json['error'] === false) { $id = $json[Document::ENTRY_ID]; $response = $id; } break; case 'getedge': $json = $response->getJson(); $options = $this->getCursorOptions(); $options['isNew'] = false; $response = Edge::createFromArray($json, $options); break; case 'edge': $json = $response->getJson(); if ($json['error'] === false) { $id = $json[Edge::ENTRY_ID]; $response = $id; } break; case 'getcollection': $json = $response->getJson(); $options = $this->getCursorOptions(); $options['isNew'] = false; $response = Collection::createFromArray($json, $options); break; case 'collection': $json = $response->getJson(); if ($json['error'] === false) { $id = $json[Collection::ENTRY_ID]; $response = $id; } break; case 'cursor': $options = $this->getCursorOptions(); $options['isNew'] = false; $response = new Cursor($this->_batch->getConnection(), $response->getJson(), $options); break; default: throw new ClientException('Could not determine response data type.'); break; } return $response; }
/** * Create an array of results from the input array * * @param array $data - incoming result * * @return void */ private function setData(array $data) { if (isset($this->_options[self::ENTRY_FLAT]) && $this->_options[self::ENTRY_FLAT]) { $this->_result = $data; } else { $this->_result = array(); if ($this->_options[self::ENTRY_TYPE] === Collection::TYPE_EDGE) { foreach ($data as $row) { $this->_result[] = Edge::createFromArray($row, $this->_options); } } else { foreach ($data as $row) { $this->_result[] = Document::createFromArray($row, $this->_options); } } } }
/** * test bulk document lookups */ public function testLookupByKeys() { $documentHandler = $this->documentHandler; $collectionHandler = $this->collectionHandler; $collection = Collection::createFromArray(array('name' => 'ArangoDB_PHP_TestSuite_TestCollection_01', 'waitForSync' => false)); $collectionHandler->add($collection); $document = Document::createFromArray(array('someAttribute' => 'someValue1', 'someOtherAttribute' => 'someOtherValue')); $documentId = $documentHandler->add($collection->getId(), $document); $document2 = Document::createFromArray(array('someAttribute' => 'someValue2', 'someOtherAttribute' => 'someOtherValue2')); $documentId2 = $documentHandler->add($collection->getId(), $document2); $document3 = Document::createFromArray(array('someAttribute' => 'someValue3', 'someOtherAttribute' => 'someOtherValue')); $documentId3 = $documentHandler->add($collection->getId(), $document3); $this->assertTrue(is_numeric($documentId), 'Did not return an id!'); $this->assertTrue(is_numeric($documentId2), 'Did not return an id!'); $this->assertTrue(is_numeric($documentId3), 'Did not return an id!'); $keys = array($documentId, $documentId2, $documentId3); $result = $collectionHandler->lookupByKeys($collection->getId(), $keys); $this->assertEquals(3, count($result)); $document = $result[0]; $this->assertInstanceOf('\\triagens\\ArangoDb\\Document', $document, "Object was not a Document!"); $this->assertEquals($documentId, $document->getId()); $this->assertEquals("someValue1", $document->someAttribute); $this->assertEquals("someOtherValue", $document->someOtherAttribute); $document = $result[1]; $this->assertInstanceOf('\\triagens\\ArangoDb\\Document', $document, "Object was not a Document!"); $this->assertEquals($documentId2, $document->getId()); $this->assertEquals("someValue2", $document->someAttribute); $this->assertEquals("someOtherValue2", $document->someOtherAttribute); $document = $result[2]; $this->assertInstanceOf('\\triagens\\ArangoDb\\Document', $document, "Object was not a Document!"); $this->assertEquals($documentId3, $document->getId()); $this->assertEquals("someValue3", $document->someAttribute); $this->assertEquals("someOtherValue", $document->someOtherAttribute); }
public function testCreateMixedBatchWithPartIds() { $edgeCollection = $this->edgeCollection; $batch = new Batch($this->connection); $this->assertInstanceOf('\\triagens\\ArangoDb\\Batch', $batch); // Create collection $connection = $this->connection; $collection = new Collection(); $collectionHandler = new CollectionHandler($connection); $name = 'ArangoDB_PHP_TestSuite_TestCollection_02'; $collection->setName($name); $batch->nextBatchPartId('testCollection1'); $response = $collectionHandler->add($collection); $this->assertTrue(is_numeric($response), 'Did not return a fake numeric id!'); $batch->process(); $resultingCollectionId = $batch->getProcessedPartResponse('testCollection1'); $testCollection1Part = $batch->getPart('testCollection1'); $this->assertTrue($testCollection1Part->getHttpCode() == 200, 'Did not return an HttpCode 200!'); $resultingCollection = $collectionHandler->get($batch->getProcessedPartResponse('testCollection1')); $resultingAttribute = $resultingCollection->getName(); $this->assertTrue($name === $resultingAttribute, 'The created collection name and resulting collection name do not match!'); $this->assertEquals(Collection::getDefaultType(), $resultingCollection->getType()); $batch = new Batch($this->connection); // Create documents $documentHandler = $this->documentHandler; $batch->nextBatchPartId('doc1'); $document = Document::createFromArray(array('someAttribute' => 'someValue', 'someOtherAttribute' => 'someOtherValue')); $documentId = $documentHandler->add($resultingCollectionId, $document); $this->assertTrue(is_numeric($documentId), 'Did not return a fake numeric id!'); for ($i = 0; $i <= 10; ++$i) { $document = Document::createFromArray(array('someAttribute' => 'someValue' . $i, 'someOtherAttribute' => 'someOtherValue2' . $i)); $documentId = $documentHandler->add($resultingCollectionId, $document); } $this->assertTrue(is_numeric($documentId), 'Did not return a fake numeric id!'); $batch->process(); // try getting processed response through batchpart $testDocument1PartResponse = $batch->getPart('doc1')->getProcessedResponse(); // try getting it from batch $testDocument2PartResponse = $batch->getProcessedPartResponse(1); $batch = new Batch($this->connection); $docId1 = explode('/', $testDocument1PartResponse); $docId2 = explode('/', $testDocument2PartResponse); $documentHandler->getById($resultingCollectionId, $docId1[1]); $documentHandler->getById($resultingCollectionId, $docId2[1]); $batch->process(); $document1 = $batch->getProcessedPartResponse(0); $document2 = $batch->getProcessedPartResponse(1); $batch = new Batch($this->connection); // test edge creation $edgeDocument = new Edge(); $edgeDocumentHandler = new EdgeHandler($connection); $edgeDocument->set('label', 'knows'); $edgeDocumentHandler->saveEdge($edgeCollection->getName(), $document1->getHandle(), $document2->getHandle(), $edgeDocument); $batch->process(); $edge = $batch->getProcessedPartResponse(0); $this->assertFalse(is_a($edge, 'triagens\\ArangoDb\\HttpResponse'), 'Edge batch creation did return an error: ' . print_r($edge, true)); $this->assertTrue($edge == !'', 'Edge batch creation did return empty string: ' . print_r($edge, true)); $batch = new Batch($this->connection); $document = new Document(); $documentHandler = new DocumentHandler($connection); $document->someAttribute = 'someValue'; $documentHandler->add($resultingCollection->getId(), $document); // set the next batchpart id $batch->nextBatchPartId('myBatchPart'); // set cursor options for the next batchpart $batch->nextBatchPartCursorOptions(array("sanitize" => true)); // set batchsize to 10, so we can test if an additional http request is done when we getAll() a bit later $statement = new Statement($connection, array("query" => '', "count" => true, "batchSize" => 10, "sanitize" => true)); $statement->setQuery('FOR a IN `ArangoDB_PHP_TestSuite_TestCollection_02` RETURN a'); $statement->execute(); $documentHandler->removeById($resultingCollectionId, $docId1[1]); $documentHandler->removeById($resultingCollectionId, $docId2[1]); $batch->nextBatchPartId('docsAfterRemoval'); $collectionHandler->getAllIds($resultingCollectionId); $batch->process(); $stmtCursor = $batch->getProcessedPartResponse('myBatchPart'); $this->assertTrue(count($stmtCursor->getAll()) == 13, 'At the time of statement execution there should be 13 documents found! Found: ' . count($stmtCursor->getAll())); // This fails but we'll just make a note because such a query is not needed to be batched. // $docsAfterRemoval=$batch->getProcessedPartResponse('docsAfterRemoval'); // $this->assertTrue(count($docsAfterRemoval) == 1, 'At the time of statement execution there should be 3 documents found! Found: '.count($stmtCursor->getAll())); // Get previously created collection and delete it, from inside a batch $batch = new Batch($this->connection); $collectionHandler->delete($resultingCollectionId); $batch->process(); }
/** * Test for correct exception codes if nonexistent objects are tried to be gotten, replaced, updated or removed */ public function testGetReplaceUpdateAndRemoveOnNonExistentObjects() { // Setup objects $documentHandler = $this->documentHandler; $document = Document::createFromArray(array('someAttribute' => 'someValue', 'someOtherAttribute' => 'someOtherValue', 'someThirdAttribute' => 'someThirdValue')); // Try to get a non-existent document out of a nonexistent collection // This should cause an exception with a code of 404 try { $e = null; $documentHandler->get('nonExistentCollection', 'nonexistentId'); } catch (\Exception $e) { // don't bother us... just give us the $e } $this->assertInstanceOf('triagens\\ArangoDb\\ServerException', $e); $this->assertTrue($e->getCode() == 404, 'Should be 404, instead got: ' . $e->getCode()); // Try to get a non-existent document out of an existent collection // This should cause an exception with a code of 404 try { $e = null; $documentHandler->get($this->collection->getId(), 'nonexistentId'); } catch (\Exception $e) { // don't bother us... just give us the $e } $this->assertInstanceOf('triagens\\ArangoDb\\ServerException', $e); $this->assertTrue($e->getCode() == 404, 'Should be 404, instead got: ' . $e->getCode()); // Try to update a non-existent document // This should cause an exception with a code of 404 try { $e = null; $documentHandler->updateById($this->collection->getId(), 'nonexistentId', $document); } catch (\Exception $e) { // don't bother us... just give us the $e } $this->assertInstanceOf('triagens\\ArangoDb\\ServerException', $e); $this->assertTrue($e->getCode() == 404, 'Should be 404, instead got: ' . $e->getCode()); // Try to replace a non-existent document // This should cause an exception with a code of 404 try { $e = null; $documentHandler->replaceById($this->collection->getId(), 'nonexistentId', $document); } catch (\Exception $e) { // don't bother us... just give us the $e } $this->assertInstanceOf('triagens\\ArangoDb\\ServerException', $e); $this->assertTrue($e->getCode() == 404, 'Should be 404, instead got: ' . $e->getCode()); // Try to remove a non-existent document // This should cause an exception with a code of 404 try { $e = null; $documentHandler->removeById($this->collection->getId(), 'nonexistentId'); } catch (\Exception $e) { // don't bother us... just give us the $e } $this->assertInstanceOf('triagens\\ArangoDb\\ServerException', $e); $this->assertTrue($e->getCode() == 404, 'Should be 404, instead got: ' . $e->getCode()); }
/** * Create an array of common neighbors from the input array * * @param array $data - array of incoming "paths" arrays * * @return void */ private function addCommonNeighborsFromArray(array $data) { $left = $data["left"]; $right = $data["right"]; if (!isset($this->_result[$left])) { $this->_result[$left] = array(); } if (!isset($this->_result[$left][$right])) { $this->_result[$left][$right] = array(); } foreach ($data["neighbors"] as $neighbor) { $this->_result[$left][$right][] = Document::createFromArray($neighbor); } }
/** * Remove document(s) by specifying an example * * This will throw on any error * * @throws Exception * * @param mixed $collectionId - collection id as string or number * @param mixed $document - the example document as a Document object or an array * @param bool|array $options - optional - an array of options. * <p>Options are :<br> * <li> * 'waitForSync' - if set to true, then all removal operations will instantly be synchronised to disk.<br> * If this is not specified, then the collection's default sync behavior will be applied. * </li> * </p> * <li>'limit' - Optional, The maximal amount of documents to return. 'skip' is applied before the limit restriction.</li> * * @return int - number of documents that were deleted * * @since 1.2 */ public function removeByExample($collectionId, $document, $options = array()) { if (is_array($document)) { $document = Document::createFromArray($document, $options); } if (!$document instanceof Document) { throw new ClientException('Invalid example document specification'); } $body = array(self::OPTION_COLLECTION => $collectionId, self::OPTION_EXAMPLE => $document->getAll(array('_ignoreHiddenAttributes' => true))); $body = $this->includeOptionsInBody($options, $body, array(ConnectionOptions::OPTION_WAIT_SYNC => $this->getConnectionOption(ConnectionOptions::OPTION_WAIT_SYNC), self::OPTION_LIMIT => null)); $response = $this->getConnection()->put(Urls::URL_REMOVE_BY_EXAMPLE, $this->json_encode_wrapper($body)); $responseArray = $response->getJson(); if ($responseArray['error'] === true) { throw new ClientException('Invalid example document specification'); } return $responseArray['deleted']; }
function &_add($oFolder, $sFilename, $oUser, $aOptions) { global $default; //$oContents = KTUtil::arrayGet($aOptions, 'contents'); $aMetadata = KTUtil::arrayGet($aOptions, 'metadata', null, false); $oDocumentType = KTUtil::arrayGet($aOptions, 'documenttype'); $sDescription = KTUtil::arrayGet($aOptions, 'description', ''); if (empty($sDescription)) { // If no document name is provided use the filename minus the extension $aFile = pathinfo($sFilename); $sDescription = isset($aFile['filename']) && !empty($aFile['filename']) ? $aFile['filename'] : $sFilename; } $oUploadChannel =& KTUploadChannel::getSingleton(); if ($oDocumentType) { $iDocumentTypeId = KTUtil::getId($oDocumentType); } else { $iDocumentTypeId = 1; } $oUploadChannel->sendMessage(new KTUploadGenericMessage(_kt('Creating database entry'))); $oDocument =& Document::createFromArray(array('name' => $sDescription, 'description' => $sDescription, 'filename' => $sFilename, 'folderid' => $oFolder->getID(), 'creatorid' => $oUser->getID(), 'documenttypeid' => $iDocumentTypeId)); $oUploadChannel->sendMessage(new KTUploadGenericMessage(_kt('Storing contents'))); $res = KTDocumentUtil::storeContents($oDocument, '', $aOptions); if (PEAR::isError($res)) { if (!PEAR::isError($oDocument)) { $oDocument->delete(); } return $res; } if (is_null($aMetadata)) { $res = KTDocumentUtil::setIncomplete($oDocument, 'metadata'); if (PEAR::isError($res)) { $oDocument->delete(); return $res; } } else { $oUploadChannel->sendMessage(new KTUploadGenericMessage(_kt('Saving metadata'))); $res = KTDocumentUtil::saveMetadata($oDocument, $aMetadata, $aOptions); if (PEAR::isError($res)) { $oDocument->delete(); return $res; } } // setIncomplete and storeContents may change the document's status or // storage_path, so now is the time to update $oDocument->update(); return $oDocument; }
try { $collectionHandler->add($collection); } catch (\Exception $e) { // collection may already exist - ignore this error for now } // create a new department $marketing = Document::createFromArray(array("name" => "Marketing")); $documentHandler->save("departments", $marketing); // create another department $finance = Document::createFromArray(array("name" => "Finance")); $documentHandler->save("departments", $finance); // create a new employee $john = Document::createFromArray(array("name" => "John")); $documentHandler->save("employees", $john); // create another employee $jane = Document::createFromArray(array("name" => "Jane")); $documentHandler->save("employees", $jane); // now insert a link between Marketing and Jane $worksFor = Edge::createFromArray(array("startDate" => "2009-06-23", "endDate" => "2014-11-12")); $edgeHandler->saveEdge("worksFor", $marketing->getHandle(), $jane->getHandle(), $worksFor); // now insert a link between Finance and Jane $worksFor = Edge::createFromArray(array("startDate" => "2014-11-12")); $edgeHandler->saveEdge("worksFor", $finance->getHandle(), $jane->getHandle(), $worksFor); // now insert a link between Finance and John $worksFor = Edge::createFromArray(array("startDate" => "2012-04-01")); $edgeHandler->saveEdge("worksFor", $finance->getHandle(), $john->getHandle(), $worksFor); } catch (ConnectException $e) { print $e . PHP_EOL; } catch (ServerException $e) { print $e . PHP_EOL; } catch (ClientException $e) {
/** * test for fulltext queries */ public function testFulltextQuery() { $this->collectionHandler = new CollectionHandler($this->connection); $documentHandler = $this->documentHandler; $collectionHandler = $this->collectionHandler; $collection = Collection::createFromArray(array('name' => 'ArangoDB_PHP_TestSuite_TestCollection_01', 'waitForSync' => true)); $collectionHandler->add($collection); $document = Document::createFromArray(array('someAttribute' => 'someValue1', 'someOtherAttribute' => 'someOtherValue')); $documentId = $documentHandler->add($collection->getId(), $document); $document2 = Document::createFromArray(array('someAttribute' => 'someValue2', 'someOtherAttribute' => 'someOtherValue2')); $documentId2 = $documentHandler->add($collection->getId(), $document2); $document3 = Document::createFromArray(array('someAttribute' => 'someValue3', 'someOtherAttribute' => 'someOtherValue')); $documentId3 = $documentHandler->add($collection->getId(), $document3); // First we test without a fulltext index and expect a 400 try { $result = $collectionHandler->fulltext($collection->getId(), "someOtherAttribute", "someOtherValue"); } catch (Exception $e) { } $this->assertTrue($e->getCode() === 400); // Now we create an index $fulltextIndexId = $collectionHandler->createFulltextIndex($collection->getId(), array("someOtherAttribute")); $fulltextIndexId = $fulltextIndexId["id"]; $cursor = $collectionHandler->fulltext($collection->getId(), "someOtherAttribute", "someOtherValue", array("index" => $fulltextIndexId)); $m = $cursor->getMetadata(); $this->assertTrue($m["count"] == 2); $this->assertTrue($m["hasMore"] == false); // Now we pass some options $cursor = $collectionHandler->fulltext($collection->getId(), "someOtherAttribute", "someOtherValue", array("index" => $fulltextIndexId, "skip" => 1)); $m = $cursor->getMetadata(); $this->assertTrue($m["count"] == 1); $this->assertTrue($m["hasMore"] == false); $cursor = $collectionHandler->fulltext($collection->getId(), "someOtherAttribute", "someOtherValue", array("batchSize" => 1)); $m = $cursor->getMetadata(); $this->assertTrue($m["count"] == 2); $this->assertTrue(count($m["result"]) == 1); $this->assertTrue($m["hasMore"] == true); }
/** * save a document to a collection * * This will add the document to the collection and return the document's id * * This will throw if the document cannot be saved * * @throws Exception * * @param mixed $collectionId - collection id as string or number * @param mixed $document - the document to be added, can be passed as a document or an array * @param bool|array $options - optional, prior to v1.2.0 this was a boolean value for create. Since v1.0.0 it's an array of options. * <p>Options are :<br> * <li>'create' - create the collection if it does not yet exist.</li> * <li>'waitForSync' - if set to true, then all removal operations will instantly be synchronised to disk / If this is not specified, then the collection's default sync behavior will be applied.</li> * </p> * * @return mixed - id of document created * @since 1.0 */ public function save($collectionId, $document, $options = array()) { // This preserves compatibility for the old create parameter. $params = array(self::OPTION_COLLECTION => $collectionId); $params = $this->validateAndIncludeOldSingleParameterInParams($options, $params, ConnectionOptions::OPTION_CREATE); $params = $this->includeOptionsInParams($options, $params, array(ConnectionOptions::OPTION_WAIT_SYNC => $this->getConnectionOption(ConnectionOptions::OPTION_WAIT_SYNC))); if (is_array($document)) { $document = Document::createFromArray($document); } $data = $document->getAll(); $url = UrlHelper::appendParamsUrl(Urls::URL_DOCUMENT, $params); $response = $this->getConnection()->post($url, $this->json_encode_wrapper($data)); $location = $response->getLocationHeader(); if (!$location) { throw new ClientException('Did not find location header in server response'); } $json = $response->getJson(); $id = UrlHelper::getDocumentIdFromLocation($location); $document->setInternalId($json[Document::ENTRY_ID]); $document->setRevision($json[Document::ENTRY_REV]); if ($id != $document->getId()) { throw new ClientException('Got an invalid response from the server'); } $document->setIsNew(false); return $document->getId(); }
/** * Bulk lookup documents by specifying an array of keys * * This will throw on any error * * @throws Exception * * @param mixed $collectionId - collection id as string or number * @param array $keys - array of document keys * @param array $options - optional array of options. * <p>Options are :<br> * <li>'_sanitize' - True to remove _id and _rev attributes from result documents. Defaults to false.</li> * <li>'_hiddenAttributes' - Set an array of hidden attributes for created documents. * </p> * * @return array - an array containing all documents found for the keys specified. * note that if for a given key not document is found, it will not be returned nor will the document's non-existence be reported. * * @since 2.6 */ public function lookupByKeys($collectionId, array $keys, $options = array()) { $body = array(self::OPTION_COLLECTION => $collectionId, self::OPTION_KEYS => $keys); $response = $this->getConnection()->put(Urls::URL_LOOKUP_BY_KEYS, $this->json_encode_wrapper($body)); $responseArray = $response->getJson(); $result = array(); foreach ($responseArray['documents'] as $document) { $result[] = Document::createFromArray($document, $options); } return $result; }