MergeHandler   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 17
c 0
b 0
f 0
dl 0
loc 41
rs 10
wmc 9

1 Method

Rating   Name   Duplication   Size   Complexity  
B autoMergeColumns() 0 31 9
1
<?php
2
/**
3
 * @name: MergeHandler
4
 * @author: JiaMeng <[email protected]>
5
 * @file: MergeHandler.php
6
 * @Date: 2025/01/XX
7
 */
8
namespace tinymeng\spreadsheet\Excel\Handler;
9
10
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
11
use tinymeng\spreadsheet\Util\WorkSheetHelper;
12
13
class MergeHandler
14
{
15
    /**
16
     * 自动合并指定字段相同值的单元格
17
     * @param Worksheet $worksheet
18
     * @param array $mergeColumns 需要合并的列字段名列表
19
     * @param array $fields 所有字段列表
20
     * @param int $rowStart 数据起始行
21
     * @param int $rowEnd 数据结束行
22
     */
23
    public static function autoMergeColumns(
24
        Worksheet $worksheet,
25
        array $mergeColumns,
26
        array $fields,
27
        int $rowStart,
28
        int $rowEnd
29
    ) {
30
        if ($rowEnd <= $rowStart) return;
31
        
32
        foreach ($mergeColumns as $fieldName) {
33
            $colIdx = array_search($fieldName, $fields);
34
            if ($colIdx === false) continue;
35
            
36
            $colLetter = WorkSheetHelper::cellName($colIdx);
0 ignored issues
show
Bug introduced by
It seems like $colIdx can also be of type string; however, parameter $columnIndex of tinymeng\spreadsheet\Uti...SheetHelper::cellName() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

36
            $colLetter = WorkSheetHelper::cellName(/** @scrutinizer ignore-type */ $colIdx);
Loading history...
37
            $lastValue = null;
38
            $mergeStart = $rowStart;
39
            
40
            for ($row = $rowStart; $row <= $rowEnd; $row++) {
41
                $cellValue = $worksheet->getCell($colLetter . $row)->getValue();
42
                if ($lastValue !== null && $cellValue !== $lastValue) {
43
                    if ($row - $mergeStart > 1) {
44
                        $worksheet->mergeCells($colLetter . $mergeStart . ':' . $colLetter . ($row - 1));
45
                    }
46
                    $mergeStart = $row;
47
                }
48
                $lastValue = $cellValue;
49
            }
50
            
51
            // 处理最后一组
52
            if ($rowEnd - $mergeStart + 1 > 1) {
53
                $worksheet->mergeCells($colLetter . $mergeStart . ':' . $colLetter . $rowEnd);
54
            }
55
        }
56
    }
57
}
58
59