-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathCursor.php
884 lines (757 loc) · 21.1 KB
/
Cursor.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
<?php
/**
* ArangoDB PHP client: result set cursor
*
* @package ArangoDBClient
* @author Jan Steemann
* @copyright Copyright 2012, triagens GmbH, Cologne, Germany
*/
namespace ArangoDBClient;
/**
* Provides access to the results of an AQL query or another statement
*
* The cursor might not contain all results in the beginning.<br>
*
* If the result set is too big to be transferred in one go, the
* cursor might issue additional HTTP requests to fetch the
* remaining results from the server.
*
* @package ArangoDBClient
* @since 0.2
*/
class Cursor implements \Iterator
{
/**
* Import $_documentClass functionality
*/
use DocumentClassable;
/**
* The connection object
*
* @var Connection
*/
private $_connection;
/**
* Cursor options
*
* @var array
*/
private $_options;
/**
* Result Data
*
* @var array
*/
private $data;
/**
* The result set
*
* @var array
*/
private $_result;
/**
* "has more" indicator - if true, the server has more results
*
* @var bool
*/
private $_hasMore;
/**
* cursor id - might be NULL if cursor does not have an id
*
* @var mixed
*/
private $_id;
/**
* current position in result set iteration (zero-based)
*
* @var int
*/
private $_position;
/**
* total length of result set (in number of documents)
*
* @var int
*/
private $_length;
/**
* full count of the result set (ignoring the outermost LIMIT)
*
* @var int
*/
private $_fullCount;
/**
* extra data (statistics) returned from the statement
*
* @var array
*/
private $_extra;
/**
* number of HTTP calls that were made to build the cursor result
*/
private $_fetches = 1;
/**
* whether or not the query result was served from the AQL query result cache
*/
private $_cached;
/**
* precalculated number of documents in the cursor, as returned by the server
*
* @var int
*/
private $_count;
/**
* result entry for cursor id
*/
const ENTRY_ID = 'id';
/**
* result entry for "hasMore" flag
*/
const ENTRY_HASMORE = 'hasMore';
/**
* result entry for result documents
*/
const ENTRY_RESULT = 'result';
/**
* result entry for extra data
*/
const ENTRY_EXTRA = 'extra';
/**
* result entry for stats
*/
const ENTRY_STATS = 'stats';
/**
* result entry for the full count (ignoring the outermost LIMIT)
*/
const FULL_COUNT = 'fullCount';
/**
* cache option entry
*/
const ENTRY_CACHE = 'cache';
/**
* cached result attribute - whether or not the result was served from the AQL query cache
*/
const ENTRY_CACHED = 'cached';
/**
* sanitize option entry
*/
const ENTRY_SANITIZE = '_sanitize';
/**
* "flat" option entry (will treat the results as a simple array, not documents)
*/
const ENTRY_FLAT = '_flat';
/**
* "objectType" option entry.
*/
const ENTRY_TYPE = 'objectType';
/**
* "baseurl" option entry.
*/
const ENTRY_BASEURL = 'baseurl';
/**
* Initialize the cursor with the first results and some metadata
*
* @param Connection $connection - connection to be used
* @param array $data - initial result data as returned by the server
* @param array $options - cursor options
*
* @throws \ArangoDBClient\ClientException
*/
public function __construct(Connection $connection, array $data, array $options)
{
$this->_connection = $connection;
$this->data = $data;
$this->_id = null;
$this->_count = null;
$this->_extra = [];
$this->_cached = false;
if (isset($data[self::ENTRY_ID])) {
$this->_id = $data[self::ENTRY_ID];
}
if (isset($data[Statement::ENTRY_COUNT])) {
$this->_count = $data[Statement::ENTRY_COUNT];
}
if (isset($data[self::ENTRY_EXTRA])) {
$this->_extra = $data[self::ENTRY_EXTRA];
if (isset($this->_extra[self::ENTRY_STATS][self::FULL_COUNT])) {
$this->_fullCount = $this->_extra[self::ENTRY_STATS][self::FULL_COUNT];
}
}
if (isset($data[self::ENTRY_CACHED])) {
$this->_cached = $data[self::ENTRY_CACHED];
}
// attribute must be there
assert(isset($data[self::ENTRY_HASMORE]));
$this->_hasMore = (bool) $data[self::ENTRY_HASMORE];
if (isset($options['_documentClass'])) {
$this->setDocumentClass($options['_documentClass']);
}
$options['_isNew'] = false;
$this->_options = $options;
$this->_result = [];
$this->add((array) $data[self::ENTRY_RESULT]);
$this->updateLength();
$this->rewind();
}
/**
* Explicitly delete the cursor
*
* This might issue an HTTP DELETE request to inform the server about
* the deletion.
*
* @throws Exception
* @return bool - true if the server acknowledged the deletion request, false otherwise
*/
public function delete()
{
if ($this->_id) {
try {
$this->_connection->delete($this->url() . '/' . $this->_id, []);
return true;
} catch (Exception $e) {
}
}
return false;
}
/**
* Get the total number of results in the cursor
*
* This might issue additional HTTP requests to fetch any outstanding
* results from the server
*
* @throws Exception
* @return int - total number of results
*/
public function getCount()
{
if ($this->_count !== null) {
return $this->_count;
}
while ($this->_hasMore) {
$this->fetchOutstanding();
}
return $this->_length;
}
/**
* Get the full count of the cursor (ignoring the outermost LIMIT)
*
* @return int - total number of results
*/
public function getFullCount()
{
return $this->_fullCount;
}
/**
* Get the cached attribute for the result set
*
* @return bool - whether or not the query result was served from the AQL query cache
*/
public function getCached()
{
return $this->_cached;
}
/**
* Get all results as an array
*
* This might issue additional HTTP requests to fetch any outstanding
* results from the server
*
* @throws Exception
* @return array - an array of all results
*/
public function getAll()
{
while ($this->_hasMore) {
$this->fetchOutstanding();
}
return $this->_result;
}
/**
* Rewind the cursor, necessary for Iterator
*
* @return void
*/
#[\ReturnTypeWillChange]
public function rewind()
{
$this->_position = 0;
}
/**
* Return the current result row, necessary for Iterator
*
* @return array - the current result row as an assoc array
*/
#[\ReturnTypeWillChange]
public function current()
{
return $this->_result[$this->_position];
}
/**
* Return the index of the current result row, necessary for Iterator
*
* @return int - the current result row index
*/
#[\ReturnTypeWillChange]
public function key()
{
return $this->_position;
}
/**
* Advance the cursor, necessary for Iterator
*
* @return void
*/
#[\ReturnTypeWillChange]
public function next()
{
++$this->_position;
}
/**
* Check if cursor can be advanced further, necessary for Iterator
*
* This might issue additional HTTP requests to fetch any outstanding
* results from the server
*
* @throws Exception
* @return bool - true if the cursor can be advanced further, false if cursor is at end
*/
#[\ReturnTypeWillChange]
public function valid()
{
if ($this->_position <= $this->_length - 1) {
// we have more results than the current position is
return true;
}
if (!$this->_hasMore || !$this->_id) {
// we don't have more results, but the cursor is exhausted
return false;
}
// need to fetch additional results from the server
$this->fetchOutstanding();
return ($this->_position <= $this->_length - 1);
}
/**
* Create an array of results from the input array
*
* @param array $data - incoming result
*
* @return void
* @throws \ArangoDBClient\ClientException
*/
private function add(array $data)
{
foreach ($this->sanitize($data) as $row) {
if (!is_array($row) || (isset($this->_options[self::ENTRY_FLAT]) && $this->_options[self::ENTRY_FLAT])) {
$this->addFlatFromArray($row);
} else {
if (!isset($this->_options['objectType'])) {
$this->addDocumentsFromArray($row);
} else {
switch ($this->_options['objectType']) {
case 'edge' :
$this->addEdgesFromArray($row);
break;
case 'vertex' :
$this->addVerticesFromArray($row);
break;
case 'path' :
$this->addPathsFromArray($row);
break;
case 'shortestPath' :
$this->addShortestPathFromArray($row);
break;
case 'distanceTo' :
$this->addDistanceToFromArray($row);
break;
case 'commonNeighbors' :
$this->addCommonNeighborsFromArray($row);
break;
case 'commonProperties' :
$this->addCommonPropertiesFromArray($row);
break;
case 'figure' :
$this->addFigureFromArray($row);
break;
default :
$this->addDocumentsFromArray($row);
break;
}
}
}
}
}
/**
* Create an array of results from the input array
*
* @param array $data - array of incoming results
*
* @return void
*/
private function addFlatFromArray($data)
{
$this->_result[] = $data;
}
/**
* Create an array of documents from the input array
*
* @param array $data - array of incoming "document" arrays
*
* @return void
* @throws \ArangoDBClient\ClientException
*/
private function addDocumentsFromArray(array $data)
{
$_documentClass = $this->_documentClass;
$this->_result[] = $_documentClass::createFromArray($data, $this->_options);
}
/**
* Create an array of paths from the input array
*
* @param array $data - array of incoming "paths" arrays
*
* @return void
* @throws \ArangoDBClient\ClientException
*/
private function addPathsFromArray(array $data)
{
$_documentClass = $this->_documentClass;
$_edgeClass = $this->_edgeClass;
$entry = [
'vertices' => [],
'edges' => [],
'source' => $_documentClass::createFromArray($data['source'], $this->_options),
'destination' => $_documentClass::createFromArray($data['destination'], $this->_options),
];
foreach ($data['vertices'] as $v) {
$entry['vertices'][] = $_documentClass::createFromArray($v, $this->_options);
}
foreach ($data['edges'] as $v) {
$entry['edges'][] = $_edgeClass::createFromArray($v, $this->_options);
}
$this->_result[] = $entry;
}
/**
* Create an array of shortest paths from the input array
*
* @param array $data - array of incoming "paths" arrays
*
* @return void
* @throws \ArangoDBClient\ClientException
*/
private function addShortestPathFromArray(array $data)
{
$_documentClass = $this->_documentClass;
$_edgeClass = $this->_edgeClass;
if (!isset($data['vertices'])) {
return;
}
$vertices = $data['vertices'];
$startVertex = $vertices[0];
$destination = $vertices[count($vertices) - 1];
$entry = [
'paths' => [],
'source' => $_documentClass::createFromArray($startVertex, $this->_options),
'distance' => $data['distance'],
'destination' => $_documentClass::createFromArray($destination, $this->_options),
];
$path = [
'vertices' => [],
'edges' => []
];
foreach ($data['vertices'] as $v) {
$path['vertices'][] = $v;
}
foreach ($data['edges'] as $v) {
$path['edges'][] = $_edgeClass::createFromArray($v, $this->_options);
}
$entry['paths'][] = $path;
$this->_result[] = $entry;
}
/**
* Create an array of distances from the input array
*
* @param array $data - array of incoming "paths" arrays
*
* @return void
*/
private function addDistanceToFromArray(array $data)
{
$entry = [
'source' => $data['startVertex'],
'distance' => $data['distance'],
'destination' => $data['vertex']
];
$this->_result[] = $entry;
}
/**
* Create an array of common neighbors from the input array
*
* @param array $data - array of incoming "paths" arrays
*
* @return void
* @throws \ArangoDBClient\ClientException
*/
private function addCommonNeighborsFromArray(array $data)
{
$_documentClass = $this->_documentClass;
$left = $data['left'];
$right = $data['right'];
if (!isset($this->_result[$left])) {
$this->_result[$left] = [];
}
if (!isset($this->_result[$left][$right])) {
$this->_result[$left][$right] = [];
}
foreach ($data['neighbors'] as $neighbor) {
$this->_result[$left][$right][] = $_documentClass::createFromArray($neighbor);
}
}
/**
* Create an array of common properties from the input array
*
* @param array $data - array of incoming "paths" arrays
*
* @return void
*/
private function addCommonPropertiesFromArray(array $data)
{
$k = array_keys($data);
$k = $k[0];
$this->_result[$k] = [];
foreach ($data[$k] as $c) {
$id = $c['_id'];
unset($c['_id']);
$this->_result[$k][$id] = $c;
}
}
/**
* Create an array of figuresfrom the input array
*
* @param array $data - array of incoming "paths" arrays
*
* @return void
*/
private function addFigureFromArray(array $data)
{
$this->_result = $data;
}
/**
* Create an array of Edges from the input array
*
* @param array $data - array of incoming "edge" arrays
*
* @return void
* @throws \ArangoDBClient\ClientException
*/
private function addEdgesFromArray(array $data)
{
$_edgeClass = $this->_edgeClass;
$this->_result[] = $_edgeClass::createFromArray($data, $this->_options);
}
/**
* Create an array of Vertex from the input array
*
* @param array $data - array of incoming "vertex" arrays
*
* @return void
* @throws \ArangoDBClient\ClientException
*/
private function addVerticesFromArray(array $data)
{
$_documentClass = $this->_documentClass;
$this->_result[] = $_documentClass::createFromArray($data, $this->_options);
}
/**
* Sanitize the result set rows
*
* This will remove the _id and _rev attributes from the results if the
* "sanitize" option is set
*
* @param array $rows - array of rows to be sanitized
*
* @return array - sanitized rows
*/
private function sanitize(array $rows)
{
$_documentClass = $this->_documentClass;
if (isset($this->_options[self::ENTRY_SANITIZE]) && $this->_options[self::ENTRY_SANITIZE]) {
foreach ($rows as $key => $value) {
if (is_array($value) && isset($value[$_documentClass::ENTRY_ID])) {
unset($rows[$key][$_documentClass::ENTRY_ID]);
}
if (is_array($value) && isset($value[$_documentClass::ENTRY_REV])) {
unset($rows[$key][$_documentClass::ENTRY_REV]);
}
}
}
return $rows;
}
/**
* Fetch outstanding results from the server
*
* @throws Exception
* @return void
*/
private function fetchOutstanding()
{
// continuation
$response = $this->_connection->post($this->url() . '/' . $this->_id, '', []);
++$this->_fetches;
$data = $response->getJson();
$this->_hasMore = (bool) $data[self::ENTRY_HASMORE];
$this->add($data[self::ENTRY_RESULT]);
if (!$this->_hasMore) {
// we have fetched the complete result set and can unset the id now
$this->_id = null;
}
$this->updateLength();
}
/**
* Set the length of the (fetched) result set
*
* @return void
*/
private function updateLength()
{
$this->_length = count($this->_result);
}
/**
* Return the base URL for the cursor
*
* @return string
*/
private function url()
{
if (isset($this->_options[self::ENTRY_BASEURL])) {
return $this->_options[self::ENTRY_BASEURL];
}
// this is the fallback
return Urls::URL_CURSOR;
}
/**
* Get a statistical figure value from the query result
*
* @param string $name - name of figure to return
*
* @return int
*/
private function getStatValue($name)
{
if (isset($this->_extra[self::ENTRY_STATS][$name])) {
return $this->_extra[self::ENTRY_STATS][$name];
}
return 0;
}
/**
* Get MetaData of the current cursor
*
* @return array
*/
public function getMetadata()
{
return $this->data;
}
/**
* Return the extra data of the query (statistics etc.). Contents of the result array
* depend on the type of query executed
*
* @return array
*/
public function getExtra()
{
return $this->_extra;
}
/**
* Return the warnings issued during query execution
*
* @return array
*/
public function getWarnings()
{
if (isset($this->_extra['warnings'])) {
return $this->_extra['warnings'];
}
return [];
}
/**
* Return the number of writes executed by the query
*
* @return int
*/
public function getWritesExecuted()
{
return $this->getStatValue('writesExecuted');
}
/**
* Return the number of ignored write operations from the query
*
* @return int
*/
public function getWritesIgnored()
{
return $this->getStatValue('writesIgnored');
}
/**
* Return the number of documents iterated over in full scans
*
* @return int
*/
public function getScannedFull()
{
return $this->getStatValue('scannedFull');
}
/**
* Return the number of documents iterated over in index scans
*
* @return int
*/
public function getScannedIndex()
{
return $this->getStatValue('scannedIndex');
}
/**
* Return the number of documents filtered by the query
*
* @return int
*/
public function getFiltered()
{
return $this->getStatValue('filtered');
}
/**
* Return the peak memory usage of the query
*
* @return int
*/
public function getPeakMemoryUsage()
{
return $this->getStatValue('peakMemoryUsage');
}
/**
* Return the execution time of the query
*
* @return float
*/
public function getExecutionTime()
{
return $this->getStatValue('executionTime');
}
/**
* Return the number of HTTP calls that were made to build the cursor result
*
* @return int
*/
public function getFetches()
{
return $this->_fetches;
}
/**
* Return the cursor id, if any
*
* @return string
*/
public function getId()
{
return $this->_id;
}
}
class_alias(Cursor::class, '\triagens\ArangoDb\Cursor');