Passed
Push — master ( 88ea13...9cfc55 )
by Sébastien
04:02
created

PDFExporter::getPsr7Response()   B

Complexity

Conditions 5
Paths 2

Size

Total Lines 28
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 8.7091

Importance

Changes 0
Metric Value
dl 0
loc 28
ccs 8
cts 17
cp 0.4706
rs 8.439
c 0
b 0
f 0
cc 5
eloc 17
nc 2
nop 1
crap 8.7091
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * Jasper report integration for PHP
7
 *
8
 * @link      https://github.com/belgattitude/soluble-jasper
9
 * @author    Vanvelthem Sébastien
10
 * @copyright Copyright (c) 2017 Vanvelthem Sébastien
11
 * @license   MIT
12
 */
13
14
namespace Soluble\Jasper\Exporter;
15
16
use Psr\Http\Message\ResponseInterface;
17
use Soluble\Jasper\Exception\IOException;
18
use Soluble\Jasper\Exception\IOPermissionException;
19
use Soluble\Jasper\Proxy\Engine\Export\JRPdfExporter;
20
use Soluble\Jasper\Proxy\Engine\JasperPrint;
21
use Soluble\Jasper\Proxy\Export\SimplePdfExporterConfiguration;
22
use Soluble\Jasper\Report;
23
use Soluble\Jasper\Runner\BridgedReportRunner;
24
use Zend\Diactoros\Response;
25
use Zend\Diactoros\Stream;
26
27
class PDFExporter
28
{
29
    /**
30
     * @var BridgedReportRunner
31
     */
32
    private $runner;
33
34
    /**
35
     * @var Report
36
     */
37
    private $report;
38
39
    /**
40
     * @var JasperPrint
41
     */
42
    private $jasperPrint;
43
44
    /**
45
     * @var JRPdfExporter
46
     */
47
    private $exporter;
48
49 1
    public function __construct(Report $report, BridgedReportRunner $runner)
50
    {
51 1
        $this->runner   = $runner;
52 1
        $this->report   = $report;
53 1
        $this->exporter = new JRPdfExporter($runner->getBridgeAdapter());
54 1
    }
55
56
    /**
57
     * @param string   $outputFile
58
     * @param string[] $pdfConfig
59
     */
60 1
    public function saveFile(string $outputFile, array $pdfConfig = null): void
61
    {
62 1
        $jasperPrint = $this->getFilledReport();
63 1
        $this->exporter->setExporterInput($jasperPrint->getJavaProxiedObject());
64 1
        $this->exporter->setExporterOutput(new \SplFileInfo($outputFile));
65 1
        if ($pdfConfig !== null) {
66
            $simplePdfConfig = $this->getPdfExporterConfiguration($pdfConfig);
67
            $this->exporter->setConfiguration($simplePdfConfig);
68
        }
69 1
        $this->exporter->exportReport();
70 1
    }
71
72
    /**
73
     * Return a new PSR-7 Response object filled with the PDF content.
74
     *
75
     * @param string[]|null $pdfConfig
76
     *
77
     * @throws IOException
78
     * @throws IOPermissionException
79
     */
80 1
    public function getPsr7Response(array $pdfConfig = null): ResponseInterface
81
    {
82 1
        $tmpFile = $this->createTempFile();
83
84
        try {
85 1
            $this->saveFile($tmpFile, $pdfConfig);
86
        } catch (\Throwable $e) {
87
            if (file_exists($tmpFile)) {
88
                unlink($tmpFile);
89
            }
90
            throw $e;
91
        }
92
93 1
        $response = new Response();
94 1
        $response = $response->withBody(new Stream($tmpFile));
95 1
        $response = $response->withHeader('Content-type', 'application/pdf');
96
97 1
        if (@unlink($tmpFile) === false) {
98
            $this->runner->getLogger()->warning(
99
                sprintf(
100
                    "Could not delete temp file '%s' after PSR7 response generation: %s.",
101
                    $tmpFile,
102
                    file_exists($tmpFile) ? 'File exists, cannot unlink' : 'File does not exists'
103
                )
104
            );
105
        }
106
107 1
        return $response;
108
    }
109
110
    /**
111
     * @param null|string $tmpDir if null use sys_get_temp_dir()
112
     * @param int|null    $mode   default to '0666'
113
     *
114
     * @throws IOException
115
     * @throws IOPermissionException
116
     */
117 1
    protected function createTempFile(?string $tmpDir=null, ?int $mode=0666): string
118
    {
119 1
        $tmpDir  = $tmpDir ?? sys_get_temp_dir();
120 1
        $tmpFile = tempnam($tmpDir, 'soluble-jasper');
121 1
        if ($tmpFile === false) {
122
            throw new IOException(sprintf(
123
                'Cannot create temporary file in %s',
124
                $tmpDir
125
            ));
126
        }
127 1
        if (chmod($tmpFile, $mode) === false) {
128
            unlink($tmpFile);
129
            throw new IOPermissionException(sprintf(
130
                'Cannot set file permission of file %s.',
131
                $tmpFile
132
            ));
133
        }
134
135 1
        return $tmpFile;
136
    }
137
138
    /**
139
     * @param string[] $config
140
     */
141
    private function getPdfExporterConfiguration(array $config): SimplePdfExporterConfiguration
0 ignored issues
show
Unused Code introduced by
The parameter $config is not used and could be removed. ( Ignorable by Annotation )

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

141
    private function getPdfExporterConfiguration(/** @scrutinizer ignore-unused */ array $config): SimplePdfExporterConfiguration

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
142
    {
143
        $pdfConfig = new SimplePdfExporterConfiguration($this->runner->getBridgeAdapter());
144
145
        return $pdfConfig;
146
    }
147
148 1
    private function getFilledReport(): JasperPrint
149
    {
150 1
        if ($this->jasperPrint === null) {
151 1
            $jasperReport      = $this->runner->compileReport($this->report);
152 1
            $this->jasperPrint = $this->runner->fillReport(
153 1
                                                    $jasperReport,
154 1
                                                    $this->report->getReportParams(),
155 1
                                                    $this->report->getDataSource()
156
            );
157
        }
158
159 1
        return $this->jasperPrint;
160
    }
161
}
162