Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1441 ariadna 1
<?php
2
 
3
namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef;
4
 
5
use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError;
6
 
7
class Filter
8
{
9
    public static function filter(array $lookupArray, mixed $matchArray, mixed $ifEmpty = null): mixed
10
    {
11
        if (!is_array($matchArray)) {
12
            return ExcelError::VALUE();
13
        }
14
 
15
        $matchArray = self::enumerateArrayKeys($matchArray);
16
 
17
        $result = (Matrix::isColumnVector($matchArray))
18
            ? self::filterByRow($lookupArray, $matchArray)
19
            : self::filterByColumn($lookupArray, $matchArray);
20
 
21
        if (empty($result)) {
22
            return $ifEmpty ?? ExcelError::CALC();
23
        }
24
 
25
        return array_values(array_map('array_values', $result));
26
    }
27
 
28
    private static function enumerateArrayKeys(array $sortArray): array
29
    {
30
        array_walk(
31
            $sortArray,
32
            function (&$columns): void {
33
                if (is_array($columns)) {
34
                    $columns = array_values($columns);
35
                }
36
            }
37
        );
38
 
39
        return array_values($sortArray);
40
    }
41
 
42
    private static function filterByRow(array $lookupArray, array $matchArray): array
43
    {
44
        $matchArray = array_values(array_column($matchArray, 0)); // @phpstan-ignore-line
45
 
46
        return array_filter(
47
            array_values($lookupArray),
48
            fn ($index): bool => (bool) $matchArray[$index],
49
            ARRAY_FILTER_USE_KEY
50
        );
51
    }
52
 
53
    private static function filterByColumn(array $lookupArray, array $matchArray): array
54
    {
55
        $lookupArray = Matrix::transpose($lookupArray);
56
 
57
        if (count($matchArray) === 1) {
58
            $matchArray = array_pop($matchArray);
59
        }
60
 
61
        array_walk(
62
            $matchArray,
63
            function (&$value): void {
64
                $value = [$value];
65
            }
66
        );
67
 
68
        $result = self::filterByRow($lookupArray, $matchArray);
69
 
70
        return Matrix::transpose($result);
71
    }
72
}