MCPcopy Create free account
hub / github.com/Rello/analytics / applyTopN

Method applyTopN

lib/Service/FlexibleStorageService.php:905–963  ·  view source on GitHub ↗

* @param list > $data * @param list ,aggregation:string}> $projection * @return list > */

(array $data, array $projection, array $option)

Source from the content-addressed store, hash-verified

903 * @return list<list<mixed>>
904 */
905 private function applyTopN(array $data, array $projection, array $option): array {
906 $columnRefs = array_column(array_column($projection, 'column'), 'ref');
907 $dimensionIndex = array_search($option['dimension']['ref'], $columnRefs, true);
908 $measureIndex = array_search($option['measure']['ref'], $columnRefs, true);
909 if ($dimensionIndex === false || $measureIndex === false) {
910 return $data;
911 }
912
913 $totals = [];
914 $order = [];
915 foreach ($data as $row) {
916 $key = json_encode($row[$dimensionIndex], JSON_THROW_ON_ERROR);
917 if (!isset($totals[$key])) {
918 $totals[$key] = '0';
919 $order[$key] = count($order);
920 }
921 $totals[$key] = $this->decimalAdd($totals[$key], (string)($row[$measureIndex] ?? '0'));
922 }
923 uksort($totals, function (string $left, string $right) use ($totals, $order, $option): int {
924 $comparison = $this->decimalCompare($totals[$left], $totals[$right]);
925 if ($comparison === 0) {
926 return $order[$left] <=> $order[$right];
927 }
928 return $option['type'] === 'top' ? -$comparison : $comparison;
929 });
930 $keep = array_fill_keys(array_slice(array_keys($totals), 0, $option['number']), true);
931 $result = [];
932 $others = [];
933 $measureIndexes = [];
934 foreach ($projection as $index => $item) {
935 if ($item['column']['role'] === 'measure') {
936 $measureIndexes[] = $index;
937 }
938 }
939 foreach ($data as $row) {
940 $key = json_encode($row[$dimensionIndex], JSON_THROW_ON_ERROR);
941 if (isset($keep[$key])) {
942 $result[] = $row;
943 continue;
944 }
945 if (!$option['others']) {
946 continue;
947 }
948 $row[$dimensionIndex] = 'others';
949 $keyParts = $row;
950 foreach ($measureIndexes as $index) {
951 unset($keyParts[$index]);
952 }
953 $othersKey = json_encode(array_values($keyParts), JSON_THROW_ON_ERROR);
954 if (!isset($others[$othersKey])) {
955 $others[$othersKey] = $row;
956 continue;
957 }
958 foreach ($measureIndexes as $index) {
959 $others[$othersKey][$index] = $this->decimalAdd((string)$others[$othersKey][$index], (string)($row[$index] ?? '0'));
960 }
961 }
962 return array_merge($result, array_values($others));

Callers 6

queryMethod · 0.95
appMin.jsFile · 0.80
report.jsFile · 0.80
dashboard.jsFile · 0.80
reference.jsFile · 0.80

Calls 3

decimalAddMethod · 0.95
decimalCompareMethod · 0.95
countFunction · 0.50

Tested by

no test coverage detected