コード例 #1
0
ファイル: Vertex.php プロジェクト: atomicjets/PHP-Rexster
 public function createInEdge($fromVertex, $label = '', array $properties = array())
 {
     if (empty($fromVertex)) {
         throw new \InvalidArgumentException("Invalid vertex id");
     }
     $data = array('_outV' => $fromVertex, '_inV' => $this->getId());
     if (!empty($label)) {
         $data['_label'] = $label;
     }
     if (!empty($properties)) {
         $data = array_merge($data, $properties);
     }
     $e = new Edge($this->getClient(), $data);
     return $e->create();
 }
コード例 #2
0
ファイル: Node.php プロジェクト: nizsheanez/kur.ru
 public function getAllEdges()
 {
     $criteria = new CDbCriteria(array('condition' => '(t.source=' . $this->id . ') or (t.target=' . $this->id . ')'));
     $model = Edge::model();
     $model->getDbCriteria()->mergeWith($criteria);
     return $model->with('target_node', 'source_node')->findAll();
 }
コード例 #3
0
 $graph->setVerticesCollection('VertexCollection');
 $graph->setEdgesCollection('EdgeCollection');
 try {
     $graphHandler->dropGraph($graph);
 } catch (\Exception $e) {
     // graph may not yet exist. ignore this error for now
 }
 $graphHandler->createGraph($graph);
 // Define some arrays to build the content of the vertices and edges
 $vertex1Array = array('_key' => 'vertex1', 'someKey1' => 'someValue1');
 $vertex2Array = array('_key' => 'vertex2', 'someKey2' => 'someValue2');
 $edge1Array = array('_key' => 'edge1', 'someEdgeKey1' => 'someEdgeValue1');
 // Create documents for 2 vertices and a connecting edge
 $vertex1 = Vertex::createFromArray($vertex1Array);
 $vertex2 = Vertex::createFromArray($vertex2Array);
 $edge1 = Edge::createFromArray($edge1Array);
 // Save the vertices
 $saveResult1 = $graphHandler->saveVertex('Graph', $vertex1);
 $saveResult2 = $graphHandler->saveVertex('Graph', $vertex2);
 // Get the vertices
 $getResult1 = $graphHandler->getVertex('Graph', 'vertex1');
 $getResult2 = $graphHandler->getVertex('Graph', 'vertex2');
 // check if vertex exists
 var_dump($graphHandler->hasVertex('Graph', 'vertex1'));
 // Save the connecting edge
 $saveEdgeResult1 = $graphHandler->saveEdge('Graph', $vertex1->getHandle(), $vertex2->getHandle(), 'somelabelValue', $edge1);
 // check if edge exists
 var_dump($graphHandler->hasEdge('Graph', 'edge1'));
 // Get the connecting edge
 $getEdgeResult1 = $graphHandler->getEdge('Graph', 'edge1');
 // Remove vertices and edges
コード例 #4
0
ファイル: GraphAsLists.php プロジェクト: EdenChan/Instances
 /**
  * Inserts the specified edge into this graph.
  *
  * @param object Edge $edge The edge to insert into this graph.
  */
 protected function insertEdge(Edge $edge)
 {
     $v = $edge->getV0()->getNumber();
     $this->adjacencyList[$v]->append($edge);
     /*
     $w = $edge->getV1()->getNumber();
     $this->adjacencyList[$w]->append(
         new Edge($this, $w, $v, $edge->getWeight()));
     */
     ++$this->numberOfEdges;
 }
コード例 #5
0
ファイル: GraphAsMatrix.php プロジェクト: EdenChan/Instances
 /**
  * Inserts the given edge into this graph.
  *
  * @param object Edge $edge The edge to insert.
  */
 protected function insertEdge(Edge $edge)
 {
     $v = $edge->getV0()->getNumber();
     $w = $edge->getV1()->getNumber();
     if ($this->matrix[array($v, $w)] !== NULL) {
         throw new ArgumentError();
     }
     if ($v == $w) {
         throw new ArgumentError();
     }
     $this->matrix[array($v, $w)] = $edge;
     $this->matrix[array($w, $v)] = $edge;
     ++$this->numberOfEdges;
 }
コード例 #6
0
 /**
  * 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;
 }
コード例 #7
0
 /**
  * Create an array of Edges from the input array
  *
  * @param array $data - array of incoming "edge" arrays
  *
  * @return void
  */
 private function addEdgesFromArray(array $data)
 {
     $this->_result[] = Edge::createFromArray($data, $this->_options);
 }
コード例 #8
0
 /**
  * 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);
             }
         }
     }
 }
コード例 #9
0
ファイル: Graph.php プロジェクト: esseara/lecomps
 public function __construct($studentId, $courseId, $em, $student)
 {
     $this->nodes = array();
     $this->edges = array();
     $lessons = array();
     $csSkill = array();
     $cognitiveState = $em->getRepository('sociaLecompsSuperBundle:Student')->getCognitiveState($studentId);
     for ($i = 0; $i < count($cognitiveState); $i++) {
         $csSkill[$i] = $cognitiveState[$i]->getSkill()->getId();
     }
     $course = $em->getRepository('sociaLecompsSuperBundle:Course')->find($courseId);
     if ($course != null) {
         $lessons = $em->getRepository('sociaLecompsSuperBundle:Lesson')->getLessons($course);
     }
     foreach ($lessons as $lesson) {
         $rk = $lesson->getRequiredSkills();
         if (count($rk) == 0) {
             $basic = $em->getRepository('sociaLecompsSuperBundle:Skill')->findBy(array('name' => 'basic knowledge'));
             $node = new Node($basic[0], $lesson);
             $this->nodes[$node->getId()] = $node;
             $node->setInCS();
             $node->setDistance(0);
             $currentNode = $this->nodes[$node->getId()];
             $currentNode->addOut($lesson->getId());
         } else {
             foreach ($rk as $skill) {
                 /*
                  * verifico se il nodo è già esistente nel grafo
                  * se lo è devo solo aggiornare gli archi
                  * se non lo è creo il nodo e poi aggiungo l'arco
                  */
                 if (array_key_exists($skill->getId(), $this->nodes)) {
                     $currentNode = $this->nodes[$skill->getId()];
                     $currentNode->addOut($lesson->getId());
                 } else {
                     $node = new Node($skill, $lesson);
                     $this->nodes[$node->getId()] = $node;
                     if (in_array($node->getId(), $csSkill)) {
                         $cs = $em->getRepository('sociaLecompsSuperBundle:CognitiveState')->findBy(array('skill' => $node->getId(), 'student' => $studentId));
                         $node->setInCS();
                         $node->setDistance(0);
                         $node->setCertanty($cs[0]->getCertainty());
                     }
                     $currentNode = $this->nodes[$skill->getId()];
                     $currentNode->addOut($lesson->getId());
                 }
             }
         }
         $ak = $lesson->getAcquiredSkills();
         foreach ($ak as $skill) {
             if (array_key_exists($skill->getId(), $this->nodes)) {
                 $currentNode = $this->nodes[$skill->getId()];
                 $currentNode->addIn($lesson->getId());
             } else {
                 $node = new Node($skill, $lesson);
                 $this->nodes[$node->getId()] = $node;
                 if (in_array($node->getId(), $csSkill)) {
                     $cs = $em->getRepository('sociaLecompsSuperBundle:CognitiveState')->findBy(array('skill' => $node->getId(), 'student' => $studentId));
                     $node->setInCS();
                     $node->setDistance(0);
                     $node->setCertanty($cs[0]->getCertainty());
                 }
                 $currentNode = $this->nodes[$skill->getId()];
                 $currentNode->addIn($lesson->getId());
             }
         }
         $edge = new Edge($lesson);
         //crea l'arco che rappresenta la lc
         $this->edges[$edge->getId()] = $edge;
         //inserisce l'arco nell'array degli archi del grafo
     }
     //Inizializza le distanze stimate di ogni nodo con il peso minimo degli archi entranti
     foreach ($this->nodes as $node) {
         foreach ($node->getIn() as $e) {
             $edge = $this->edges[$e];
             if ($edge->getWeight() < $node->getDistance()) {
                 $node->setDistance($edge->getWeight());
             }
         }
     }
 }
コード例 #10
0
ファイル: Graph.php プロジェクト: siparker/pagerank
 /**
  * @param Edge $edge
  */
 public function addEdge(Edge $edge)
 {
     $this->edges[] = $edge;
     $this->addNode($edge->getFrom());
     $this->addNode($edge->getTo());
 }
コード例 #11
0
    } 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) {
    print $e . PHP_EOL;
}
コード例 #12
0
ファイル: DigraphAsLists.php プロジェクト: EdenChan/Instances
 /**
  * Inserts the specified edge into this graph.
  *
  * @param object Edge $edge The edge to insert into this graph.
  */
 protected function insertEdge(Edge $edge)
 {
     $v = $edge->getV0()->getNumber();
     $this->adjacencyList[$v]->append($edge);
     ++$this->numberOfEdges;
 }
コード例 #13
0
ファイル: Edge.php プロジェクト: EdenChan/Instances
    public function __toString()
    {
        $s = '';
        $s .= "Edge{" . str($this->v0);
        if ($this->isDirected()) {
            $s .= '->' . str($this->v1);
        } else {
            $s .= '--' . str($this->v1);
        }
        if ($this->weight !== NULL) {
            $s .= ', weight = ' . str($this->weight);
        }
        $s .= '}';
        return $s;
    }
    /**
     * Main program.
     *
     * @param array $args Command-line arguments.
     * @return integer Zero on success; non-zero on failure.
     */
    public static function main($args)
    {
        printf("Edge main program.\n");
        $status = 0;
        return $status;
    }
}
if (realpath($argv[0]) == realpath(__FILE__)) {
    exit(Edge::main(array_slice($argv, 1)));
}
コード例 #14
0
 /**
  * Try to create, head and delete a edge
  */
 public function testCreateHeadAndDeleteEdgeWithRevision()
 {
     $connection = $this->connection;
     $edgeHandler = new EdgeHandler($connection);
     $edgeCollection = $this->edgeCollection;
     $document1 = new Document();
     $document2 = new Document();
     $documentHandler = new DocumentHandler($connection);
     $edgeDocument = new Edge();
     $document1->someAttribute = 'someValue1';
     $document2->someAttribute = 'someValue2';
     $documentHandler->add('ArangoDBPHPTestSuiteTestCollection01', $document1);
     $documentHandler->add('ArangoDBPHPTestSuiteTestCollection01', $document2);
     $documentHandle1 = $document1->getHandle();
     $documentHandle2 = $document2->getHandle();
     $edgeDocument->set('label', 'knows');
     $edgeId = $edgeHandler->saveEdge($edgeCollection->getName(), $documentHandle1, $documentHandle2, $edgeDocument);
     try {
         $edgeHandler->getHead($edgeCollection->getId(), $edgeId, "12345", true);
     } catch (\Exception $e412) {
     }
     $this->assertEquals($e412->getCode(), 412);
     try {
         $edgeHandler->getHead($edgeCollection->getId(), "notExisting");
     } catch (\Exception $e404) {
     }
     $this->assertEquals($e404->getCode(), 404);
     $result304 = $edgeHandler->getHead($edgeCollection->getId(), $edgeId, $edgeDocument->getRevision(), false);
     $this->assertEquals($result304["etag"], '"' . $edgeDocument->getRevision() . '"');
     $this->assertEquals($result304["content-length"], 0);
     $this->assertEquals($result304["httpCode"], 304);
     $result200 = $edgeHandler->getHead($edgeCollection->getId(), $edgeId, $edgeDocument->getRevision(), true);
     $this->assertEquals($result200["etag"], '"' . $edgeDocument->getRevision() . '"');
     $this->assertNotEquals($result200["content-length"], 0);
     $this->assertEquals($result200["httpCode"], 200);
     $documentHandler->delete($document1);
     $documentHandler->delete($document2);
     $edgeHandler->deleteById($edgeCollection->getName(), $edgeId);
 }
コード例 #15
0
ファイル: recipe_plugin.php プロジェクト: yakar/yioop
 /**
  *  Compares the weights of two edges and returns -1, 0, 1 depending
  *  on which is the largest first, equal, or second
  *
  * @param Edge $edge1 first Edge to compare
  * @param Edge $edge2 second Edge to compare
  * @return int -1,-0,1 as described above
  */
 function compare($edge1, $edge2)
 {
     $values1 = $edge1->getCost();
     $values2 = $edge2->getCost();
     if ($values1 == $values2) {
         return 0;
     }
     return $values1 > $values2 ? -1 : 1;
 }
コード例 #16
0
ファイル: test.php プロジェクト: Auguraculums/graphdb-testing
}
$nv = get_next_int64($fp);
$ne = get_next_int64($fp);
$off = get_int64_array($fp, $nv + 1);
$ind = get_int64_array($fp, $ne);
$wgt = get_int64_array($fp, $ne);
fclose($fp);
print "Inserting into DB...\n";
//$batch = new Batch($connection);
//$batch->activate();
$vertices = array_fill(0, $nv, "-1");
$time_start = microtime(true);
for ($v = 0; $v < $nv; $v++) {
    $s = $vertices[$v];
    if ($s == "-1") {
        $s = new_vertex($documents, $u, $nv);
        $vertices[$v] = $s;
    }
    for ($i = $off[$v]; $i < $off[$v + 1]; $i++) {
        $u = $ind[$i];
        $d = $vertices[$u];
        if ($d == "-1") {
            $d = new_vertex($documents, $u, $nv);
            $vertices[$u] = $d;
        }
        $edg = new Edge();
        $edg->set("weight", $wgt[$i]);
        $edges->saveEdge($edge, $s, $d, $edg, true);
    }
}
//$batch->process();
コード例 #17
0
 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();
 }
コード例 #18
0
 /**
  * test for replacing a edge using replace() with wrong encoding
  * We expect an exception here:
  *
  * @expectedException \triagens\ArangoDb\ClientException
  */
 public function testReplaceEdgeWithWrongEncoding()
 {
     $edgeHandler = $this->edgeHandler;
     $edge = Edge::createFromArray(array('someAttribute' => 'someValue', 'someOtherAttribute' => 'someOtherValue'));
     $edgeId = $edgeHandler->add($this->collection->getId(), $edge);
     $this->assertTrue(is_numeric($edgeId), 'Did not return an id!');
     // inject wrong encoding
     $isoKey = iconv("UTF-8", "ISO-8859-1//TRANSLIT", "someWrongEncododedAttribute");
     $isoValue = iconv("UTF-8", "ISO-8859-1//TRANSLIT", "someWrongEncodedValueü");
     $edge->set($isoKey, $isoValue);
     $edge->set('someOtherAttribute', 'someOtherValue2');
     $result = $edgeHandler->replace($edge);
     $this->assertTrue($result);
     $resultingEdge = $edgeHandler->get($this->collection->getId(), $edgeId);
     $this->assertObjectHasAttribute('_id', $resultingEdge, '_id field should exist, empty or with an id');
     $this->assertTrue($resultingEdge->someAttribute == 'someValue2', 'Should be :someValue2, is: ' . $resultingEdge->someAttribute);
     $this->assertTrue($resultingEdge->someOtherAttribute == 'someOtherValue2', 'Should be :someOtherValue2, is: ' . $resultingEdge->someOtherAttribute);
     $response = $edgeHandler->delete($resultingEdge);
     $this->assertTrue($response, 'Delete should return true!');
 }
コード例 #19
0
 public function createGraph()
 {
     $vertex1 = Vertex::createFromArray($this->vertex1Array);
     $vertex2 = Vertex::createFromArray($this->vertex2Array);
     $vertex3 = Vertex::createFromArray($this->vertex3Array);
     $vertex4 = Vertex::createFromArray($this->vertex4Array);
     $vertex5 = Vertex::createFromArray($this->vertex5Array);
     $edge1 = Edge::createFromArray($this->edge1Array);
     $edge2 = Edge::createFromArray($this->edge2Array);
     $edge3 = Edge::createFromArray($this->edge3Array);
     $edge4 = Edge::createFromArray($this->edge4Array);
     $edge5 = Edge::createFromArray($this->edge5Array);
     $this->graphHandler->saveVertex($this->graphName, $vertex1);
     $this->graphHandler->saveVertex($this->graphName, $vertex2);
     $this->graphHandler->saveVertex($this->graphName, $vertex3);
     $this->graphHandler->saveVertex($this->graphName, $vertex4);
     $this->graphHandler->saveVertex($this->graphName, $vertex5);
     $this->graphHandler->getVertex($this->graphName, $this->vertex1Name);
     $this->graphHandler->getVertex($this->graphName, $this->vertex2Name);
     $this->graphHandler->getVertex($this->graphName, $this->vertex3Name);
     $this->graphHandler->getVertex($this->graphName, $this->vertex4Name);
     $this->graphHandler->getVertex($this->graphName, $this->vertex5Name);
     $this->graphHandler->saveEdge($this->graphName, $this->vertexCollectionName . "/" . $this->vertex1Name, $this->vertexCollectionName . "/" . $this->vertex2Name, $this->edgeLabel1, $edge1);
     $this->graphHandler->saveEdge($this->graphName, $this->vertexCollectionName . "/" . $this->vertex2Name, $this->vertexCollectionName . "/" . $this->vertex3Name, $this->edgeLabel2, $edge2);
     $this->graphHandler->saveEdge($this->graphName, $this->vertexCollectionName . "/" . $this->vertex2Name, $this->vertexCollectionName . "/" . $this->vertex4Name, $this->edgeLabel3, $edge3);
     $this->graphHandler->saveEdge($this->graphName, $this->vertexCollectionName . "/" . $this->vertex5Name, $this->vertexCollectionName . "/" . $this->vertex1Name, $this->edgeLabel4, $edge4);
     $this->graphHandler->saveEdge($this->graphName, $this->vertexCollectionName . "/" . $this->vertex5Name, $this->vertexCollectionName . "/" . $this->vertex2Name, $this->edgeLabel5, $edge5);
 }
コード例 #20
0
 /**
  * Tests if the updateEdge method accepts an instance of Graph as first argument and extracts the graph name out of it.
  */
 public function testUpdateEdgeWithGraphInstance()
 {
     $this->createGraph();
     $result = $this->graphHandler->updateEdge($this->graph, $this->edge1Name, '', Edge::createFromArray(array('_key' => 'foobar')));
     $this->assertTrue($result);
 }
 /**
  */
 public function testsaveGetUpdateReplaceRemoveEdge()
 {
     $edge1 = Edge::createFromArray($this->edge1Array);
     $ex = null;
     try {
         $this->graphHandler->saveEdge($this->graphName, $this->v1 . "/" . $this->vertex1Array["_key"], $this->v1 . "/" . $this->vertex1Array["_key"], null, $edge1);
     } catch (Exception $e) {
         $ex = $e->getMessage();
     }
     $this->assertTrue($ex == 'A collection must be provided.');
     $this->createGraph();
     $this->graphHandler->saveEdge($this->graphName, $this->v1 . "/" . $this->vertex1Array["_key"], $this->v4 . "/" . $this->vertex4Array["_key"], null, array(), $this->e1);
     $ex = null;
     try {
         $this->graphHandler->getEdge($this->graphName, $this->edge1Array["_key"]);
     } catch (Exception $e) {
         $ex = $e->getMessage();
     }
     $this->assertTrue($ex == 'A collection must be provided.');
     $v1 = $this->graphHandler->getEdge($this->graphName, $this->edge1Array["_key"], array(), $this->e1);
     $v2 = $this->graphHandler->getEdge($this->graphName, $this->e1 . "/" . $this->edge1Array["_key"], array());
     $this->assertTrue($v1->getInternalKey() == $v2->getInternalKey());
     $v1 = $this->graphHandler->getEdge($this->graphName, $this->e1 . "/" . $this->edge1Array["_key"], array());
     $v = Edge::createFromArray($this->edge1Array);
     $v->setRevision($v1->getRevision());
     $ex = null;
     try {
         $this->graphHandler->replaceEdge($this->graphName, $this->edge1Array["_key"], null, $v, array());
     } catch (Exception $e) {
         $ex = $e->getMessage();
     }
     $this->assertTrue($ex == 'A collection must be provided.');
     $v1 = $this->graphHandler->getEdge($this->graphName, $this->e1 . "/" . $this->edge1Array["_key"], array());
     $v = Edge::createFromArray($this->edge1Array);
     $v->setRevision($v1->getRevision());
     $this->assertTrue($this->graphHandler->replaceEdge($this->graphName, $this->edge1Array["_key"], null, $v, array('revision' => $v1->getRevision()), $this->e1));
     $v1 = $this->graphHandler->getEdge($this->graphName, $this->e1 . "/" . $this->edge1Array["_key"], array());
     $v = Edge::createFromArray($this->edge1Array);
     $v->setRevision($v1->getRevision());
     $this->assertTrue($this->graphHandler->replaceEdge($this->graphName, $this->e1 . "/" . $this->edge1Array["_key"], null, $v, array('revision' => true)));
     $ex = null;
     try {
         $this->graphHandler->updateEdge($this->graphName, $this->edge1Array["_key"], null, $v, array());
     } catch (Exception $e) {
         $ex = $e->getMessage();
     }
     $this->assertTrue($ex == 'A collection must be provided.');
     $v1 = $this->graphHandler->getEdge($this->graphName, $this->e1 . "/" . $this->edge1Array["_key"], array());
     $v = Edge::createFromArray($this->edge1Array);
     $v->setRevision($v1->getRevision());
     $this->assertTrue($this->graphHandler->updateEdge($this->graphName, $this->edge1Array["_key"], null, $v, array('revision' => true), $this->e1));
     $v1 = $this->graphHandler->getEdge($this->graphName, $this->e1 . "/" . $this->edge1Array["_key"], array());
     $v = Edge::createFromArray($this->edge1Array);
     $v->setRevision($v1->getRevision());
     $this->assertTrue($this->graphHandler->updateEdge($this->graphName, $this->e1 . "/" . $this->edge1Array["_key"], null, $v, array('revision' => $v1->getRevision())));
     //removeVertex($graph, $vertexId, $revision = null, $options = array(), $collection = null)
     $ex = null;
     try {
         $this->graphHandler->removeEdge($this->graphName, $this->edge1Array["_key"], null, array());
     } catch (Exception $e) {
         $ex = $e->getMessage();
     }
     $this->assertTrue($ex == 'A collection must be provided.');
     $v1 = $this->graphHandler->getVertex($this->graphName, $this->e1 . "/" . $this->edge1Array["_key"], array());
     $this->assertTrue($this->graphHandler->removeEdge($this->graphName, $this->e1 . "/" . $this->edge1Array["_key"], $v1->getRevision(), array()));
 }
コード例 #22
0
 /**
  * Update an existing edge in a graph, identified by graph name and edge id
  *
  * This will update the edge on the server
  *
  * This will throw if the edge cannot be updated
  *
  * If policy is set to error (locally or globally through the ConnectionOptions)
  * and the passed edge-document has a _rev value set, the database will check
  * that the revision of the to-be-replaced document is the same as the one given.<br><br>
  *
  * @throws Exception
  *
  * @param mixed  $graph     - graph name as a string or instance of Graph
  * @param mixed  $edgeId    - edge id as string or number
  * @param mixed  $label     - label for the edge or ''
  * @param Edge   $document  - patch edge-document which contains the attributes and values to be updated
  * @param mixed  $options   optional, array of options (see below)
  * <p>
  * <li><b>policy</b> - update policy to be used in case of conflict ('error', 'last' or NULL [use default])</li>
  * <li><b>keepNull</b> - can be used to instruct ArangoDB to delete existing attributes instead setting their values to null. Defaults to true (keep attributes when set to null)</li>
  * <li><b>waitForSync</b> - can be used to force synchronisation of the document update operation to disk even in case that the waitForSync flag had been disabled for the entire collection</li>
  * </p>
  * @param string $collection  - if one uses a graph with more than one vertex collection one must provide the collection                          
  *
  * @return bool - always true, will throw if there is an error
  * @since 1.2
  */
 public function updateEdge($graph, $edgeId, $label, Edge $document, $options = array(), $collection = null)
 {
     if ($graph instanceof Graph) {
         $graph = $graph->getKey();
     }
     $parts = explode("/", $edgeId);
     if (count($parts) === 2) {
         $edgeId = $parts[1];
         $collection = $parts[0];
     }
     if (count($this->getEdgeCollections($graph)) !== 1 && $collection === null) {
         throw new ClientException('A collection must be provided.');
     } else {
         if (count($this->getEdgeCollections($graph)) === 1 && $collection === null) {
             $collection = $this->getEdgeCollections($graph);
             $collection = $collection[0];
         }
     }
     $options = array_merge(array(self::OPTION_REVISION => false), $options);
     // This preserves compatibility for the old policy parameter.
     $params = array();
     $params = $this->validateAndIncludeOldSingleParameterInParams($options, $params, ConnectionOptions::OPTION_UPDATE_POLICY);
     $params = $this->includeOptionsInParams($options, $params, array('waitForSync' => $this->getConnectionOption(ConnectionOptions::OPTION_WAIT_SYNC), 'keepNull' => true));
     $policy = null;
     //Include the revision for conditional updates if required
     if ($options[self::OPTION_REVISION] === true) {
         $revision = $document->getRevision();
         if (!is_null($revision)) {
             $params[ConnectionOptions::OPTION_REVISION] = $revision;
         }
     } elseif ($options[self::OPTION_REVISION]) {
         $params[ConnectionOptions::OPTION_REVISION] = $options[self::OPTION_REVISION];
     }
     if (!is_null($label)) {
         $document->set('$label', $label);
     }
     $url = UrlHelper::buildUrl(Urls::URL_GRAPH, array($graph, Urls::URLPART_EDGE, $collection, $edgeId));
     $url = UrlHelper::appendParamsUrl($url, $params);
     $result = $this->getConnection()->patch($url, $this->json_encode_wrapper($document->getAll()));
     $json = $result->getJson();
     $edge = $json['edge'];
     $document->setRevision($edge[Edge::ENTRY_REV]);
     return true;
 }
コード例 #23
0
 /**
  * save an edge to an edge-collection
  *
  * This will save the edge to the collection and return the edges-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      $from         - from vertex
  * @param mixed      $to           - to vertex
  * @param mixed      $document     - the edge-document to be added, can be passed as an object 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.<br>
  *                                 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 saveEdge($collectionId, $from, $to, $document, $options = array())
 {
     if ($collectionId instanceof Collection) {
         $collectionId = $collectionId->getName();
     }
     if (is_array($document)) {
         $document = Edge::createFromArray($document);
     }
     $document->setFrom($from);
     $document->setTo($to);
     $params = array(self::OPTION_COLLECTION => $collectionId, self::OPTION_FROM => $document->getFrom(), self::OPTION_TO => $document->getTo());
     $params = $this->validateAndIncludeOldSingleParameterInParams($options, $params, ConnectionOptions::OPTION_CREATE);
     $params = $this->includeOptionsInParams($options, $params, array(ConnectionOptions::OPTION_WAIT_SYNC => $this->getConnectionOption(ConnectionOptions::OPTION_WAIT_SYNC)));
     $data = $document->getAll();
     $url = UrlHelper::appendParamsUrl(Urls::URL_EDGE, $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[Edge::ENTRY_ID]);
     $document->setRevision($json[Edge::ENTRY_REV]);
     if ($id != $document->getId()) {
         throw new ClientException('Got an invalid response from the server');
     }
     $document->setIsNew(false);
     return $document->getId();
 }