-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTableArray.php
More file actions
1789 lines (1674 loc) · 54.3 KB
/
Copy pathTableArray.php
File metadata and controls
1789 lines (1674 loc) · 54.3 KB
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
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
//Comment out the following line to use the class without a namespace
namespace Jspit;
/**
.---------------------------------------------------------------------------.
| Software: Function Collection for Table-Arrays |
| Version: 2.6.1 |
| Date: 2022-01-11 |
| PHPVersion >= 7.0 |
| ------------------------------------------------------------------------- |
| Copyright © 2018..2022 Peter Junk (alias jspit). All Rights Reserved. |
| ------------------------------------------------------------------------- |
| License: Distributed under the Lesser General Public License (LGPL) |
| http://www.gnu.org/copyleft/lesser.html |
| This program is distributed in the hope that it will be useful - WITHOUT |
| ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
| FITNESS FOR A PARTICULAR PURPOSE. |
'---------------------------------------------------------------------------'
*/
class TableArray extends \ArrayIterator implements \JsonSerializable ,\Countable
{
private $userFct = [];
private $sqlSort = []; //internal
private $selectKeys = null; //array with valid keys after SELECT, default null = All
private static $arr2d; //use from unGroup
private $data = []; //2.dim
protected static $csvDefaultOptions = [
"file" => "",
"bom" => true,
"title" => false,
"delimiter" => ',',
"enclosure" => '"',
"escape" => "\\",
"eol" => "\r\n",
];
private $csvOptions;
const CHECK_DATA_DURING_CONSTRUCT = false;
const SEPARATOR = "\x02";
const BOM = "\xef\xbb\xbf";
const VERSION = "2.6.1";
/*
* @param mixed : table array or iterator
* @param mixed : $filter string or array or callable
* @throws InvalidArgumentException
*/
final public function __construct($data = [], $filter = null){
if(is_array($data)){
$this->data = $data;
}
elseif($data instanceof TableArray){
$this->data = $data->fetchAll();
}
//iterable?
elseif($data instanceof \Traversable){
$this->data = iterator_to_array($data);
}
else{
$msg = "Parameter for ".__METHOD__." must be a array or iterable";
throw new \InvalidArgumentException($msg);
}
//optional parameter 2 : string with key-path or array with keys to table-array
//or callable
if(is_callable($filter)){
$this->data = self::arrayFilterRecursive($this->data, $filter);
}
elseif($filter !== null){
$keyPathToData = $filter;
if(is_string($keyPathToData) AND $keyPathToData != ""){
$keyPathToData = max(explode(',',$keyPathToData),explode('.',$keyPathToData));
}
foreach($keyPathToData as $key){
if(array_key_exists($key, $this->data)) {
$this->data = $this->data[$key];
}
else {
$msg = "Parameter 2 for ".__METHOD__." must be a path with valid keys";
throw new \InvalidArgumentException($msg);
}
}
}
$firstRow = reset($this->data);
if(is_object($firstRow)){
$firstRow = (array)$firstRow;
foreach($this->data as $i => $row){
$this->data[$i] = (array)$row;
}
}
mb_internal_encoding("UTF-8");
$this->userFct = [
'ABS' => 'abs',
'UPPER' => 'mb_strtoupper',
'LOWER' => 'mb_strtolower',
'FIRSTUPPER' => function($val){
return mb_strtoupper(mb_substr($val, 0, 1)).mb_substr($val, 1);
},
'FORMAT' => 'sprintf', //par: 'format',field,[field]
'DATEFORMAT' => function($format,$date,$options=""){
if(is_numeric($date)){
//Timestamp
if(stripos($options,'ms') !== false) {
//millisecond timestamp
$date = (int)($date/1000);
}
$date = date_create()->setTimestamp($date);
if(stripos($options,'utc') !== false){
$date->setTimeZone(new \DateTimeZone('UTC'));
}
}
elseif(is_string($date)) $date = date_create($date);
if($date instanceOf \DateTime) {
return $date->format($format);
}
return "?";
},
'REPLACE' => 'str_replace', //par: 'search','replace',fieldname
'SUBSTR' => 'mb_substr', //par: fieldname,'start',['length']
'LIKE' => function($val,$likePattern){ //case insensitiv
$pattern = preg_quote($likePattern,"~");
$pattern = strtr($pattern, ['%' => '.*?', '_' => '.']);
return preg_match('~^'.$pattern.'$~i',$val);
},
'INTVAL' => 'intval',
'FLOATVAL' => function($val, $dec_point = ".", $thousands_sep = ""){
if($thousands_sep !== "") {
$val = str_replace($thousands_sep,'',$val);
}
if($dec_point !== ".") {
$val = str_replace($dec_point,'.',$val);
}
return floatval($val);
},
'TRIM' => 'trim', //par: fieldName[,'$character_mask']
'SCALE' => function($val, $factor = 1, $add = 0, $format = null){
$val = $val * $factor + $add;
if(is_string($format)) {
$val = sprintf($format, $val);
}
return $val;
},
'NULLCOUNT' => function(...$params){
$sum = 0;
foreach($params as $arg){
$sum += (int)($arg === NULL);
}
return $sum;
},
'CONCAT' => function(...$params){
return implode("",$params);
},
'IMPLODE' => function($arr,$delim=','){
if(!is_array($arr)) return $arr;
$s = '';
array_walk_recursive(
$arr,
function($v,$k) use(&$s,$delim){$s .= $v.$delim;}
);
return trim($s,$delim);
},
'SPLIT' => function($val,$delim = ' ',$number = 0){
$parts = explode($delim, $val);
return array_key_exists($number, $parts) ? $parts[$number] : "";
}
];
//csv options
$this->csvOptions = self::$csvDefaultOptions;
}
/*
* create a instance
* @param $data : 2 dim array, iterator or tableArray Instance
* @param mixed : $filter string or array or callable
* @return instance of tableArray
*/
public static function create($data = [],$filter = null,...$addpar){
return new static($data, $filter,...$addpar);
}
/*
* create a instance from JSON-String
* @param $jsonStr : represents a 2-dimensional array
* @param mixed : $filter string or array or callable
* @return instance of tableArray
*/
public static function createFromJson($jsonStr, $filter = null){
//remove annoying characters how BOM from start + end
//also processes JSONP strings
$jsonStr = preg_replace(['~^[^\[\{]+~u',"~[^\]\}]+$~u"],'',$jsonStr);
return new static(json_decode($jsonStr, true),$filter);
}
/*
* create a instance from XML
* @param $xml: xml-String or SimpleXML Object
* @param $xpath: xpath-String (optional)
* @return instance of tableArray
* @throws InvalidArgumentException
*/
public static function createFromXML($xml, $strXPath = null){
if(is_string($xml)) {
$xml = simplexml_load_string($xml);
}
if(!is_object($xml)) {
$msg = "Parameter must be a valid XML for ".__METHOD__;
throw new \InvalidArgumentException($msg);
}
//register Namespaces
foreach($xml->getDocNamespaces(TRUE) as $shortcut=>$namespace){
$ok = $xml->registerXPathNamespace($shortcut,$namespace );
}
//handle xPath
if(!empty($strXPath)) {
$xml = $xml->xpath($strXPath);
if(empty($xml)){
$msg = "2. Parameter must be a valid XPath for ".__METHOD__;
throw new \InvalidArgumentException($msg);
}
}
//create a array
$array = [];
foreach($xml as $element) {
$array[] = json_decode(str_replace("{}",'""',json_encode($element)), true);
}
return new static($array);
}
/*
* create from a numerical 1 dimensional array
* @param $array 1 dim array
* @param $delimiter delimiter for split rows
* delimter one char, handle as csv
* delimiter 2-4 chars, handle with explode
* delimter >= 5 chars use as regular expression e.g '/^(\d+) (\d+):(\d+):(\d+)/'
* delimter >= 5 chars and regular expression after s use preg_split
* e.g 's/ +/' 2 or more spaces
*/
public static function createFromOneDimArray(array $array, $delimiter = ""){
$data = [];
$lenDelim = strlen($delimiter);
$isDelimRegExSplit = $isDelimRegEx = $regExWithNamedGroups = false;
if($lenDelim >= 5){
//check regex
if(substr($delimiter,0,1) == "s"){
$isDelimRegExSplit = @preg_match(substr($delimiter,1), '') !== false;
}
else {
$isDelimRegEx = @preg_match($delimiter, '') !== false;
$regExWithNamedGroups = $isDelimRegEx && preg_match("/\(\?P?[<']/",$delimiter) == 1;
}
}
foreach($array as $key => $value){
if($lenDelim == 0){
$data[] = [$key, $value];
}
elseif($lenDelim == 1) {
//csv
$option = self::$csvDefaultOptions;
$delimiter = $delimiter ?: $option['delimiter'];
$data[] = str_getcsv($value, $delimiter, $option['enclosure'], $option['escape']);
}
elseif($lenDelim < 5) {
$data[] = explode($delimiter, $value);
}
elseif($isDelimRegEx){
//handle regex
if(preg_match($delimiter, $value, $match)){
$countMatch = count($match);
if($countMatch == 1) $row = [$key,$match[0]];
elseif($countMatch == 2) $row = [$key,$match[1]];
elseif($regExWithNamedGroups) {
$row = array_filter($match,'is_string',ARRAY_FILTER_USE_KEY);
}
else $row = array_slice($match,1);
}
else {
//error
$msg = "Wrong 2.Parameter '".$delimiter."' for ".__METHOD__;
throw new \InvalidArgumentException($msg);
}
$data[] = $row;
}
elseif($isDelimRegExSplit){
$data[] = preg_split(substr($delimiter,1), $value);
}
else {
//error
$msg = "Wrong 2.Parameter '".$delimiter."' for ".__METHOD__;
throw new \InvalidArgumentException($msg);
}
}
return new static($data);
}
/*
* create from string how get from file
* @param string $input
* @param string $regExRow for split rows
* @param string $regExSplitLines for split lines
* @throws InvalidArgumentException
*/
public static function createFromString($input, $regExRow = ',', $regExSplitLines = '/\R/' ){
$arr = @preg_split($regExSplitLines,$input,-1,PREG_SPLIT_NO_EMPTY);
if(!is_array($arr)) {
//error
$msg = "3.Parameter '".$regExSplitLines."' is not a valid RegEx for ".__METHOD__;
throw new \InvalidArgumentException($msg);
}
$arr = array_filter($arr); //remove empty values
return self::createFromOneDimArray($arr, $regExRow);
}
/*
* create from string how get from file
* @param string $file Filename or Wrapper
* @return object
* csv options must set with tableArray::setCsvDefaultOptions
* @throws InvalidArgumentException
*/
public static function createFromCsvFile($file = null){
$file = $file ?: self::$csvDefaultOptions['file'];
$del = self::$csvDefaultOptions['delimiter'];
$enc = self::$csvDefaultOptions['enclosure'];
$esc = self::$csvDefaultOptions['escape'];
if($fp = @fopen($file,'r')){
$data = [];
while (($row = fgetcsv($fp,0,$del,$enc,$esc)) !== FALSE) {
$data[] = $row;
}
fclose($fp);
}
else{
//error fopen
$errors = error_get_last();
error_clear_last();
throw new \InvalidArgumentException($errors['message']);
}
$data[0][0] = str_replace(self::BOM,"",$data[0][0]);
$objTableArray = new static($data);
if(self::$csvDefaultOptions['title']){
$objTableArray->firstRowToKey();
}
return $objTableArray;
}
/*
* create from grouped json-string or grouped array
* @param string $input
* @param array $keys : array of names for groupkeys
* @throws InvalidArgumentException
*/
public static function createFromGroupedArray($input, array $keys = ['key']){
if(is_string($input)) {
$input = json_decode($input, true);
if(!is_array($input)) {
//error
$msg = __METHOD__.": Wrong parameter input (invalid JSON)";
throw new \InvalidArgumentException($msg);
}
}
return new static(self::unGroup($input, $keys));
}
/*
* set default options for CSV
* @param array options
* @return true if ok, false if error
*/
public static function setCsvDefaultOptions(array $options) {
if($options == array_intersect_key($options, self::$csvDefaultOptions)){
self::$csvDefaultOptions = array_merge(self::$csvDefaultOptions,$options);
return true;
}
return false;
}
/*
* check if data is a array with table-structure
* @param $data : array
* @return true ok or false
*/
public static function check(array $data){
$keys = null;
foreach($data as $row){
if(is_object($row)) $row = (array)$row;
if(!is_array($row)) return false;
$curKeys = array_keys($row);
if($keys === null) $keys = $curKeys;
elseif($curKeys != $keys) return false;
}
return true;
}
/**
* get keys from all rows
*/
public static function allRowKeys(array $data){
if(!is_array(reset($data))) {
//dimension <2
return false;
}
$allFields = [];
foreach($data as $row){
$allFields += $row;
}
return array_keys($allFields);
}
/*
* ungroup data with array of given keys
* @param array $array : input
* @param array $keys : names for group keys
* @return array
*/
public static function unGroup(array $array, array $keys){
self::$arr2d = [];
return self::groupedTo2D($array, $keys, []);
}
/**
* match strings with wildcards * and ?
* @param string $pattern : String with wildcards how '*.2.?'
* @param string $string : string how 'a.1.2.c'
* @return bool
*/
public static function wildcardMatch($pattern, $string){
$pattern = preg_quote($pattern,'/');
$pattern = str_replace( ['\*','\?'] , ['.*','[^.]*'], $pattern);
return (bool)preg_match( '/^' . $pattern . '$/' , $string );
}
/**
* Returns all filtered sub-arrays
* @param array $arr
* @param callable $filter param $current, $key, $it
* @return array
*/
public static function arrayFilterRecursive(array $arr,callable $filter){
$res = array();
$it = new \RecursiveIteratorIterator(
new \RecursiveArrayIterator($arr),\RecursiveIteratorIterator::SELF_FIRST
);
foreach($it as $current){
if(is_array($current)){
$key = self::getFlatKeyFromIterator($it);
if($filter($current, $key, $it)) {
$res[$key] = $current;
}
}
}
return $res;
}
/*
* add a userfuction (closure)
* @param string $name
* @param string $function : closure
* @return $this
*/
public function addSqlFunction($name, $function){
$this->userFct[$name] = $function;
return $this;
}
public function addSqlFunctionFromArray(array $functions){
$this->userFct = array_merge($this->userFct, $functions);
return $this;
}
/*
* get a userfunction
* @param string $name
* @return closure or false if error
*/
public function getSqlFunction($name){
return isset($this->userFct[$name])
? $this->userFct[$name]
: false;
}
/*
* sort with uasort
* @param string $sqlOrderTerm: a string how for SQL OrderBy
* @return $this
*/
public function orderBy($sqlOrderTerm){
if(empty($this->data)) return $this;
$this->sqlSort = $this->setSort($sqlOrderTerm);
//uasort($this->data,array($this,"sortFunction"));
usort($this->data,array($this,"sortFunction"));
return $this;
}
/*
* set select
* @param string or array
* @return $this
* @throws InvalidArgumentException
*/
public function select($colKeys){
if(empty($this->data)) return $this;
if(is_array($colKeys)) $colKeys = implode(",", $colKeys);
if(!is_string($colKeys)) {
$msg = "Parameter must array or string ".__METHOD__;
throw new \InvalidArgumentException($msg);
}
if($colKeys == "*") {
$this->selectKeys = null;
return $this;
}
//validate
if(strpbrk($colKeys,";|+<>=*/") !== false){
$msg = "forbidden char in '($colKeys' ".__METHOD__;
throw new \InvalidArgumentException($msg);
}
//prepare and explode terms
$validFieldNames = [];
$firstDataRow = reset($this->data);
$selectFileds = [];
foreach($this->splitarg($colKeys) as $termObj){
//termObj with ->name, ->as, ->fct, ->fpar, ->term
if($fct = $termObj->fct) {
//function call
if(!array_key_exists($fct,$this->userFct)){
$msg = "Unknown Function '".$fct."' ".__METHOD__;
throw new \InvalidArgumentException($msg);
}
$parObjects = $this->splitarg($termObj->fpar);
//check if fields ok and collect in a array
$parameters = [];
foreach($parObjects as $parObj){
$trimStr = trim($parObj->term,'\'"');
if($parObj->term == $trimStr AND !array_key_exists($trimStr,$firstDataRow)){
$msg = "Unknown Parameter-Fieldname '$trimStr' ".__METHOD__;
throw new \InvalidArgumentException($msg);
}
$parameters[] = $parObj->term;
}
$nameAs = $termObj->as;
foreach($this->data as $keyData => $row){
//current parameters
$curPar = [];
foreach($parameters as $par){
$trimStr = trim($par,'\'"');
$curPar[] = $trimStr == $par ? $row[$par] : $trimStr;
}
$this->data[$keyData][$nameAs] = call_user_func_array(
$this->userFct[$fct],
$curPar
);
}
$selectFileds[] = $nameAs;
$validFieldNames[] = $nameAs;
}
else {
if(array_key_exists($termObj->name,$firstDataRow)) {
$fieldName = $termObj->name;
if($nameAs = $termObj->as){
foreach($this->data as $keyData => $row){
$this->data[$keyData][$nameAs] = $row[$fieldName];
}
$selectFileds[] = $nameAs;
$validFieldNames[] = $nameAs;
}
else {
$selectFileds[] = $fieldName;
}
}
else {
$msg = "Unknown fieldname '$termObj->name' ".__METHOD__;
throw new \InvalidArgumentException($msg);
}
}
}
$this->selectKeys = $selectFileds;
return $this;
}
/*
* filter all rows with field is like all elements from array
* @param $fieldName: key from a column
* @param $inList : List of like-Terms
* @return $this
*/
public function filterLikeAll($fieldName, $inList, $preserveKey = false){
return $this->filterLike($fieldName, $inList, $preserveKey, true);
}
/*
* filter all rows with field is like any element from array
* @param $fieldName: key from a column
* @param $inList : List of like-Terms
* @return $this
*/
public function filterLikeIn($fieldName, $inList, $preserveKey = false){
return $this->filterLike($fieldName, $inList,$preserveKey, false);
}
/*
* filter all rows with field = value, other remove
* @param $field: fieldname or array(field => value)
* @param @value: the value if $field
* @return $this
*/
public function filterEqual($field, $value = null)
{
if(is_string($field)) {
$field = [$field => $value];
}
foreach($this->data as $key => $row){
if(array_intersect_assoc($field, $row) !== $field){
unset($this->data[$key]);
}
}
return $this;
}
/*
* filter all rows with field is unique from array
* @param $fieldNames: array with fieldNames or null for all
* @return $this
* @throws InvalidArgumentException
*/
public function filterUnique(array $fieldNames = null){
if($fieldNames === null){
//all fields
foreach($this->data as $key => $row){
$keyFound = array_search($row,$this->data);
if($keyFound != $key) {
unset($this->data[$key]);
}
}
}
else {
$invalidFieldName = $this->invalidFieldNames($fieldNames);
if($invalidFieldName){
$msg = "Unknown fieldname '$invalidFieldName' ".__METHOD__;
throw new \InvalidArgumentException($msg);
}
$filterCols = [];
$flipFields = array_flip($fieldNames);
foreach($this->data as $key => $row){
$fieldsFromRow = array_intersect_key($row,$flipFields);
if(in_array($fieldsFromRow, $filterCols)) {
unset($this->data[$key]);
}
else {
$filterCols[] = $fieldsFromRow;
}
}
}
$this->data = array_values($this->data);
return $this;
}
/*
* filterGroupAggregate
* @param $aggregates: array with $fieldName => AggFunction
* @param $groups: array with fieldnames for groups
* @return $this
* @throws InvalidArgumentException
*/
public function filterGroupAggregate(array $aggregates, array $groups = [], $delim = ","){
if(empty($this->data)) return $this;
//check if $aggFields and $groups valid
$firstRow = reset($this->data);
$fileldsFirstRow = array_keys($firstRow);
$validAggFunctions = ['min','max','sum','avg','count','concat','array','json'];
$aggFields = [];
foreach($aggregates as $aggFieldName => $aggFunction){
$aggFields[] = $aggFieldName;
$aggregates[$aggFieldName] = strtolower($aggFunction);
//Check if the function is implemented
if(array_search(strtolower($aggFunction),$validAggFunctions) === false){
$msg = "Aggregate function '$aggFunction' is not implemented ".__METHOD__;
throw new \InvalidArgumentException($msg);
}
}
$iGroupsAggFields = array_intersect($groups,$aggFields);
if(!empty($iGroupsAggFields)) {
$msg = "Group-Field '".$iGroupsAggFields[0]. "'cannot be aggregated ".__METHOD__;
throw new \InvalidArgumentException($msg);
}
$groupsAndAggFileds = array_merge($groups,$aggFields);
if(array_intersect($groupsAndAggFileds,$fileldsFirstRow) != $groupsAndAggFileds){
$msg = "Unknown fieldname ".__METHOD__;
throw new \InvalidArgumentException($msg);
}
$newData = [];
foreach($this->data as $rowKey => $row){
//create groupkey
$groupkey = "";
foreach($groups as $fieldName) {
if($groupkey !== "") $groupkey .= self::SEPARATOR;
$groupkey .= $row[$fieldName];
}
if(!isset($newData[$groupkey])) {
//set start values
$newData[$groupkey] = $row;
foreach($aggregates as $aggFieldName => $aggFunction){
$startValue = 0;
if($aggFunction == 'min' OR $aggFunction == 'max')
$startValue = $row[$aggFieldName];
elseif($aggFunction == 'concat') $startValue = "";
elseif($aggFunction == 'array' OR $aggFunction == 'json') $startValue = [];
$newData[$groupkey][$aggFieldName] = $startValue;
if($aggFunction == 'avg') {
$newData[$groupkey][$aggFieldName.self::SEPARATOR.'count'] = 0;
}
}
}
$nonGroupsAndAggFields = array_diff(array_keys($row),$groupsAndAggFileds);
foreach($aggregates as $aggFieldName => $aggFunction){
if(($aggFunction == "sum" OR $aggFunction == "avg") AND is_numeric($row[$aggFieldName])){
$newData[$groupkey][$aggFieldName] += $row[$aggFieldName];
if($aggFunction == "avg"){
$newData[$groupkey][$aggFieldName.self::SEPARATOR.'count'] += 1;
}
}
elseif($aggFunction == "max"
AND $row[$aggFieldName] > $newData[$groupkey][$aggFieldName]) {
//set rest
foreach($nonGroupsAndAggFields as $fieldName){
$newData[$groupkey][$fieldName] = $row[$fieldName];
}
//$newData[$groupkey] = array_diff_key($row,$aggregates);
$newData[$groupkey][$aggFieldName] = $row[$aggFieldName];
}
elseif($aggFunction == "min"
AND $row[$aggFieldName] < $newData[$groupkey][$aggFieldName]) {
//set rest
foreach($nonGroupsAndAggFields as $fieldName){
$newData[$groupkey][$fieldName] = $row[$fieldName];
}
$newData[$groupkey][$aggFieldName] = $row[$aggFieldName];
}
elseif($aggFunction == "count") {
$newData[$groupkey][$aggFieldName] += 1;
}
elseif($aggFunction == 'concat') {
$curDelim = $newData[$groupkey][$aggFieldName] !== "" ? $delim : "";
$newData[$groupkey][$aggFieldName] .= $curDelim.$row[$aggFieldName];
}
elseif($aggFunction == 'array' OR $aggFunction == 'json') {
$newData[$groupkey][$aggFieldName][] = $row[$aggFieldName];
}
}
}
//final handling AVG = sum/count
foreach($aggregates as $aggFieldName => $aggFunction){
if($aggFunction == 'avg'){
foreach($newData as $keyRow => $row){
$count = $row[$aggFieldName.self::SEPARATOR.'count'];
unset($newData[$keyRow][$aggFieldName.self::SEPARATOR.'count']);
$newData[$keyRow][$aggFieldName] = ($count > 0) ? $row[$aggFieldName]/$count : 0.0;
}
}
if($aggFunction == 'json'){
foreach($newData as $keyRow => $row){
$newData[$keyRow][$aggFieldName] = json_encode($row[$aggFieldName]);
}
}
}
$this->data = array_values($newData);
return $this;
}
/*
* filter all rows if $callback returns true
* @param $callback: userfunction with parameter $row
* if returnvalue from $callback is false current row will delete
* if $callback == null: remove all rows with a null value
* @return $this
*/
public function filter($callback = null){
if(empty($this->data)) return $this;
foreach($this->data as $key => $row){
if($callback === null){
if(!in_array(null,$row)) continue;
}
else {
if($callback($row)) continue;
}
unset($this->data[$key]);
}
$this->data = array_values($this->data);
return $this;
}
/*
* walk over all rows
* @param $callback: userfunction with parameter $row, $key, $userParam
* must return new array $row
* if returnvalue from $callback is false current row will delete
* if $callback == null: remove all rows with a null value
* @return $this
*/
public function walk($callback, $userParam = null){
if(empty($this->data)) return $this;
foreach($this->data as $key => $row){
$newRow = $callback($row, $key, $userParam);
$this->data[$key] = $newRow;
}
return $this;
}
/*
* transposes the array (switch rows and columns)
* @return $this
*/
public function transpose(){
if(empty($this->data)) return $this;
$transArr = [];
foreach($this->data as $keyRow => $subArr) {
foreach($subArr as $keyCol => $value) {
$transArr[$keyCol][$keyRow] = $value;
}
}
$this->data = $transArr;
return $this;
}
/**
* merge array
* @param mixed $data : 2 dim array, iterator or tableArray Instance
* @return $this
* @throws Error
*/
public function merge($data){
try{
$dataArr = self::create($data)->fetchAll();
}
catch (Exception $e) {
throw $e;
}
$this->data = array_merge_recursive($this->data, $dataArr);
$this->mk_rectify();
return $this;
}
/**
* rectify: realizes uniform keys in all rows by adding missing keys
* @return $this
* @throws InvalidArgumentException
*/
public function rectify() {
if(!$this->mk_rectify()){
$msg = "array structure need minimal dimension 2 ".__METHOD__;
throw new \InvalidArgumentException($msg);
}
return $this;
}
/**
* Get all child-arrays with keys defined in array of keyPatterns
* @param array $keyPatterns : array with flatten keys with wildcards * and ?
* @param bool $addFlatKeys : if true, add flatkeys
* @return $this
*/
public function collectChilds(array $keyPatterns, $addFlatKeys = false){
$iterator = new \RecursiveIteratorIterator(
new \RecursiveArrayIterator($this->data),\RecursiveIteratorIterator::SELF_FIRST
);
$this->data = [];
foreach($iterator as $subarr){
if(is_array($subarr)){
$countConditions = count($keyPatterns);
foreach($keyPatterns as $keyPattern){
$arrFlatKeys = array_keys($this->arrayFlatten($subarr,"."));
foreach($arrFlatKeys as $flatKey){
if(self::wildcardMatch($keyPattern, $flatKey)) {
--$countConditions;
break;
}
}
}
if($countConditions === 0) {
if($addFlatKeys){
$keys = self::getFlatKeyFromIterator($iterator);
$this->data[$keys] = $subarr;
}
else{
$this->data[] = $subarr;
}
}
}
}
return $this;
}
/*
* inner Join On
* @param $ref array Reference
* @param $idRef name id for ON from Reference-Array
* @param $refId name id Basis-Array
* @return $this
*/
public function innerJoinOn($ref, $tableAlias, $idRef, $refId){
return $this->joinOn($ref, $tableAlias, $idRef, $refId, 'inner');
}
/*
* left Join On
* @param $ref array Reference
* @param $idRef name id for ON from Reference-Array
* @param $refId name id Basis-Array
* @return $this
*/
public function leftJoinOn($ref, $tableAlias, $idRef, $refId){
return $this->joinOn($ref, $tableAlias, $idRef, $refId, 'left');
}
/*
* convert to pivot table
* @param $group Field name for grouping
* @param $pivot Field name for pivot
* @param $case Field name for case
* @return $this
*/
public function pivot($group, $pivot, $case){
$this->data = $this->fetchAll();
$pivKeys = [];
foreach($this->data as $row){
$pivKeys[] = $pivot.'.'.$row[$case];
}
$piv = [];
foreach($pivKeys as $key){
$piv[$key] = null;
}
$newData = [];
foreach($this->data as $row){
$newData[$row[$group]][$group] = $row[$group];
$pivKey = $pivot.'.'.$row[$case];
$newData[$row[$group]][$pivKey] = $row[$pivot];
}
foreach($newData as $key => $row){
$newData[$key] += $piv;
}
$this->data = $newData;
return $this;
}
/*
* delete all rows < number
* @param integer number
* @return $this
*/
public function offset($number){
$i = 0;
foreach($this->data as $key => $row){
if($i >= $number) break;
unset($this->data[$key]);
$i++;
}
$this->data = array_values($this->data);
return $this;
}
/*
* delete all rows > number
* @param integer number
* for number <0 count from end
* @return $this
*/
public function limit($number){
if($number >= 0){
$i = 0;
foreach($this->data as $key => $row){
$i++;
if($i <= $number) continue;
unset($this->data[$key]);
}
$this->data = array_values($this->data);
return $this;
}
else {
return $this->offset($this->count()+$number);
}
}
/*
* add Keys from data as new column