Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
122 / 122
100.00% covered (success)
100.00%
15 / 15
CRAP
100.00% covered (success)
100.00%
1 / 1
ExcelFileFaker
100.00% covered (success)
100.00%
122 / 122
100.00% covered (success)
100.00%
15 / 15
29
100.00% covered (success)
100.00%
1 / 1
 createOriginalFilename
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 createMimeType
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isSupported
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 createResource
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
1
 contentTypes
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 rootRels
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 workbook
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 workbookRels
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 styles
100.00% covered (success)
100.00%
38 / 38
100.00% covered (success)
100.00%
1 / 1
7
 sheet
100.00% covered (success)
100.00%
34 / 34
100.00% covered (success)
100.00%
1 / 1
9
 excelDate
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 columnLetter
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 cellReference
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 stringCell
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 numberCell
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2namespace Apie\Faker\FileFakers;
3
4use Apie\Faker\Interfaces\ApieFileFaker;
5use Apie\Faker\Tabular\ColumnType;
6use Apie\Faker\Tabular\RandomRecords;
7use DateTimeImmutable;
8use Faker\Generator;
9use ZipStream\ZipStream;
10
11/**
12 * Generates a xlsx file with a random set of columns, a header row and random records in a randomly picked style.
13 */
14final class ExcelFileFaker implements ApieFileFaker
15{
16    private const STYLE_COUNT_OFFSET = 2;
17
18    private const WIDTHS = [
19        'Name' => 24,
20        'Email' => 32,
21        'City' => 20,
22        'Company' => 28,
23        'Country' => 18,
24        'Phone' => 20,
25        'Quantity' => 12,
26        'Age' => 8,
27        'Price' => 14,
28        'Rating' => 10,
29        'Created at' => 14,
30        'Birthday' => 14,
31    ];
32
33    /** @var list<array{headerFill: string, headerFont: string, font: string, size: int, zebra: ?string, border: string}> */
34    private const STYLES = [
35        ['headerFill' => 'FF1F4E78', 'headerFont' => 'FFFFFFFF', 'font' => 'Calibri', 'size' => 11, 'zebra' => 'FFDDEBF7', 'border' => 'FFBFBFBF'],
36        ['headerFill' => 'FF375623', 'headerFont' => 'FFFFFFFF', 'font' => 'Arial', 'size' => 10, 'zebra' => 'FFE2EFDA', 'border' => 'FFA9D08E'],
37        ['headerFill' => 'FFC00000', 'headerFont' => 'FFFFFFFF', 'font' => 'Verdana', 'size' => 10, 'zebra' => null, 'border' => 'FF7F7F7F'],
38        ['headerFill' => 'FFFFE699', 'headerFont' => 'FF000000', 'font' => 'Cambria', 'size' => 12, 'zebra' => 'FFFFF2CC', 'border' => 'FFBF8F00'],
39        ['headerFill' => 'FF404040', 'headerFont' => 'FFFFFFFF', 'font' => 'Consolas', 'size' => 10, 'zebra' => 'FFF2F2F2', 'border' => 'FF404040'],
40        ['headerFill' => 'FF7030A0', 'headerFont' => 'FFFFFFFF', 'font' => 'Calibri', 'size' => 11, 'zebra' => null, 'border' => 'FFD9D2E9'],
41    ];
42
43    public function createOriginalFilename(Generator $faker): string
44    {
45        return $faker->word() . '.xlsx';
46    }
47
48    public function createMimeType(): string
49    {
50        return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
51    }
52
53    public static function isSupported(): bool
54    {
55        return true;
56    }
57
58    /** @return resource */
59    public function createResource(Generator $faker, string $originalFilename, string $mimeType): mixed
60    {
61        $records = RandomRecords::create($faker);
62        $style = $faker->randomElement(self::STYLES);
63
64        $resource = tmpfile();
65        $zipstream = new ZipStream(
66            outputStream: $resource,
67            sendHttpHeaders: false,
68            outputName: $originalFilename,
69            contentType: $mimeType,
70            defaultEnableZeroHeader: false,
71            enableZip64: false,
72        );
73        $zipstream->addFile('[Content_Types].xml', $this->contentTypes());
74        $zipstream->addFile('_rels/.rels', $this->rootRels());
75        $zipstream->addFile('xl/workbook.xml', $this->workbook());
76        $zipstream->addFile('xl/_rels/workbook.xml.rels', $this->workbookRels());
77        $zipstream->addFile('xl/styles.xml', $this->styles($style));
78        $zipstream->addFile('xl/worksheets/sheet1.xml', $this->sheet($records, $style['zebra'] !== null));
79        $zipstream->finish();
80
81        return $resource;
82    }
83
84    private const XML = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
85
86    private function contentTypes(): string
87    {
88        return self::XML
89            . '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
90            . '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
91            . '<Default Extension="xml" ContentType="application/xml"/>'
92            . '<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>'
93            . '<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>'
94            . '<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>'
95            . '</Types>';
96    }
97
98    private function rootRels(): string
99    {
100        return self::XML
101            . '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
102            . '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>'
103            . '</Relationships>';
104    }
105
106    private function workbook(): string
107    {
108        return self::XML
109            . '<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'
110            . '<sheets><sheet name="Sheet1" sheetId="1" r:id="rId1"/></sheets>'
111            . '</workbook>';
112    }
113
114    private function workbookRels(): string
115    {
116        return self::XML
117            . '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
118            . '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>'
119            . '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>'
120            . '</Relationships>';
121    }
122
123    /**
124     * Cell format 0 is the default, 1 the header. After that: 4 types for normal rows followed by 4 types for zebra rows.
125     *
126     * @param array{headerFill: string, headerFont: string, font: string, size: int, zebra: ?string, border: string} $style
127     */
128    private function styles(array $style): string
129    {
130        // number formats per column type: general, #,##0, #,##0.00, custom date
131        $numFmtIds = [
132            ColumnType::Text->value => 0,
133            ColumnType::Integer->value => 3,
134            ColumnType::Decimal->value => 4,
135            ColumnType::Date->value => 164,
136        ];
137        $xfs = '<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>'
138            . '<xf numFmtId="0" fontId="1" fillId="2" borderId="1" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="center" vertical="center"/></xf>';
139        foreach ([0, 1] as $zebra) {
140            foreach ($numFmtIds as $type => $numFmtId) {
141                $alignment = $type === ColumnType::Text->value ? '' : '<alignment horizontal="right"/>';
142                $xfs .= '<xf numFmtId="' . $numFmtId . '" fontId="0" fillId="' . ($zebra && $style['zebra'] ? 3 : 0)
143                    . '" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1"'
144                    . ($alignment === '' ? '/>' : ' applyAlignment="1">' . $alignment . '</xf>');
145            }
146        }
147        $font = htmlspecialchars($style['font'], ENT_XML1);
148        $border = '<color rgb="' . $style['border'] . '"/>';
149
150        return self::XML
151            . '<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
152            . '<numFmts count="1"><numFmt numFmtId="164" formatCode="yyyy\-mm\-dd"/></numFmts>'
153            . '<fonts count="2">'
154            . '<font><sz val="' . $style['size'] . '"/><name val="' . $font . '"/></font>'
155            . '<font><b/><sz val="' . $style['size'] . '"/><color rgb="' . $style['headerFont'] . '"/><name val="' . $font . '"/></font>'
156            . '</fonts>'
157            . '<fills count="4">'
158            . '<fill><patternFill patternType="none"/></fill>'
159            . '<fill><patternFill patternType="gray125"/></fill>'
160            . '<fill><patternFill patternType="solid"><fgColor rgb="' . $style['headerFill'] . '"/><bgColor indexed="64"/></patternFill></fill>'
161            . '<fill><patternFill patternType="solid"><fgColor rgb="' . ($style['zebra'] ?? 'FFFFFFFF') . '"/><bgColor indexed="64"/></patternFill></fill>'
162            . '</fills>'
163            . '<borders count="2">'
164            . '<border><left/><right/><top/><bottom/><diagonal/></border>'
165            . '<border><left style="thin">' . $border . '</left><right style="thin">' . $border . '</right>'
166            . '<top style="thin">' . $border . '</top><bottom style="thin">' . $border . '</bottom><diagonal/></border>'
167            . '</borders>'
168            . '<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>'
169            . '<cellXfs count="' . (self::STYLE_COUNT_OFFSET + 8) . '">' . $xfs . '</cellXfs>'
170            . '<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>'
171            . '</styleSheet>';
172    }
173
174    private function sheet(RandomRecords $records, bool $zebra): string
175    {
176        $columns = $records->getColumns();
177        $cols = '';
178        $data = '<row r="1" ht="22" customHeight="1">';
179        $index = 0;
180        foreach ($columns as $column => $type) {
181            $number = $index + 1;
182            $cols .= '<col min="' . $number . '" max="' . $number . '" width="' . self::WIDTHS[$column] . '" customWidth="1"/>';
183            $data .= $this->stringCell($this->cellReference($index, 1), $column, 1);
184            $index++;
185        }
186        $data .= '</row>';
187        $row = 2;
188        foreach ($records as $record) {
189            $offset = $zebra && $row % 2 === 1 ? 4 : 0;
190            $data .= '<row r="' . $row . '">';
191            $index = 0;
192            foreach ($record as $column => $value) {
193                $reference = $this->cellReference($index++, $row);
194                $styleId = self::STYLE_COUNT_OFFSET + $offset + $columns[$column]->value;
195                $data .= match (true) {
196                    $value instanceof DateTimeImmutable => $this->numberCell($reference, $this->excelDate($value), $styleId),
197                    is_string($value) => $this->stringCell($reference, $value, $styleId),
198                    default => $this->numberCell($reference, $value, $styleId),
199                };
200            }
201            $data .= '</row>';
202            $row++;
203        }
204        $rows = $records->getRowCount();
205        $lastColumn = $this->columnLetter(count($columns) - 1);
206
207        return self::XML
208            . '<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
209            . '<dimension ref="A1:' . $lastColumn . ($rows + 1) . '"/>'
210            . '<sheetViews><sheetView workbookViewId="0"><pane ySplit="1" topLeftCell="A2" activePane="bottomLeft" state="frozen"/></sheetView></sheetViews>'
211            . '<sheetFormatPr defaultRowHeight="15"/>'
212            . '<cols>' . $cols . '</cols>'
213            . '<sheetData>' . $data . '</sheetData>'
214            . '<autoFilter ref="A1:' . $lastColumn . ($rows + 1) . '"/>'
215            . '</worksheet>';
216    }
217
218    private function excelDate(DateTimeImmutable $date): int
219    {
220        // days since 1899-12-30, which is the Excel epoch
221        return intdiv($date->getTimestamp(), 86400) + 25569;
222    }
223
224    private function columnLetter(int $index): string
225    {
226        return chr(ord('A') + $index);
227    }
228
229    private function cellReference(int $column, int $row): string
230    {
231        return $this->columnLetter($column) . $row;
232    }
233
234    private function stringCell(string $reference, string $value, int $style): string
235    {
236        return '<c r="' . $reference . '" s="' . $style . '" t="inlineStr"><is><t>'
237            . htmlspecialchars($value, ENT_XML1 | ENT_QUOTES | ENT_SUBSTITUTE)
238            . '</t></is></c>';
239    }
240
241    private function numberCell(string $reference, int|float $value, int $style): string
242    {
243        return '<c r="' . $reference . '" s="' . $style . '"><v>' . $value . '</v></c>';
244    }
245}