Failed Conditions
Push — master ( d2dc84...8e498d )
by Adrien
07:27
created

TestWithSpreadsheet   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 2
eloc 14
dl 0
loc 35
rs 10
c 1
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A readSpreadsheet() 0 14 1
A readExport() 0 11 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace ApplicationTest\Traits;
6
7
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
8
use PhpOffice\PhpSpreadsheet\Spreadsheet;
9
use ZipArchive;
10
11
trait TestWithSpreadsheet
12
{
13
    abstract public static function assertTrue($condition, string $message = ''): void;
14
15
    abstract public static function assertStringStartsWith(string $prefix, string $string, string $message = ''): void;
16
17
    abstract public static function assertFileExists(string $filename, string $message = ''): void;
18
19
    private function readExport(string $hostname, string $url): Spreadsheet
20
    {
21
        $baseUrl = 'https://' . $hostname . '/data/export/';
22
23
        self::assertStringStartsWith($baseUrl, $url, 'must be absolute URL');
24
25
        // Make sure the XLSX file was generated on disk
26
        $path = 'htdocs/data/export/' . str_replace($baseUrl, '', $url);
27
        self::assertFileExists($path, 'exported file must exist on disk');
28
29
        return $this->readSpreadsheet($path);
30
    }
31
32
    private function readSpreadsheet(string $filename): Spreadsheet
33
    {
34
        // Assert that it is a valid ZIP file to prevent PhpSpreadsheet from hanging
35
        $zip = new ZipArchive();
36
        $res = $zip->open($filename, ZipArchive::CHECKCONS);
37
        self::assertTrue($res, 'exported Excel should be a valid ZIP file');
38
        $zip->close();
39
40
        // Re-read it
41
        $reader = new Xlsx();
42
        $spreadsheet = $reader->load($filename);
43
        unlink($filename);
44
45
        return $spreadsheet;
46
    }
47
}
48