Passed
Push — master ( 59967b...68c83b )
by Sébastien
06:19
created

PDFExporter::getPsr7Response()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 31
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 10.5

Importance

Changes 0
Metric Value
dl 0
loc 31
ccs 9
cts 18
cp 0.5
rs 8.439
c 0
b 0
f 0
cc 6
eloc 18
nc 6
nop 2
crap 10.5
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 3
    public function __construct(Report $report, BridgedReportRunner $runner)
50
    {
51 3
        $this->runner   = $runner;
52 3
        $this->report   = $report;
53 3
        $this->exporter = new JRPdfExporter($runner->getBridgeAdapter());
54 3
    }
55
56
    /**
57
     * @param string   $outputFile
58
     * @param string[] $pdfConfig
59
     */
60 3
    public function saveFile(string $outputFile, array $pdfConfig = null): void
61
    {
62 3
        $jasperPrint = $this->getFilledReport();
63 3
        $this->exporter->setExporterInput($jasperPrint->getJavaProxiedObject());
64 3
        $this->exporter->setExporterOutput(new \SplFileInfo($outputFile));
65 3
        if ($pdfConfig !== null) {
66 3
            $simplePdfConfig = $this->getPdfExporterConfiguration($pdfConfig);
67 3
            $this->exporter->setConfiguration($simplePdfConfig);
68
        }
69 3
        $this->exporter->exportReport();
70 3
    }
71
72
    /**
73
     * Return a new PSR-7 Response object filled with the PDF content.
74
     *
75
     * @param string[]|null     $pdfConfig
76
     * @param ResponseInterface $response  initial response
77
     *
78
     * @throws IOException
79
     * @throws IOPermissionException
80
     */
81 3
    public function getPsr7Response(array $pdfConfig = null, ResponseInterface $response=null): ResponseInterface
82
    {
83 3
        $tmpFile = $this->createTempFile();
84
85
        try {
86 3
            $this->saveFile($tmpFile, $pdfConfig);
87
        } catch (\Throwable $e) {
88
            if (file_exists($tmpFile)) {
89
                unlink($tmpFile);
90
            }
91
            throw $e;
92
        }
93
94 3
        if ($response === null) {
95 1
            $response = new Response();
96
        }
97
98 3
        $response = $response->withBody(new Stream($tmpFile));
99 3
        $response = $response->withHeader('Content-type', 'application/pdf');
100
101 3
        if (@unlink($tmpFile) === false) {
102
            $this->runner->getLogger()->warning(
103
                sprintf(
104
                    "Could not delete temp file '%s' after PSR7 response generation: %s.",
105
                    $tmpFile,
106
                    file_exists($tmpFile) ? 'File exists, cannot unlink' : 'File does not exists'
107
                )
108
            );
109
        }
110
111 3
        return $response;
112
    }
113
114
    /**
115
     * @param null|string $tmpDir if null use sys_get_temp_dir()
116
     * @param int|null    $mode   default to '0666'
117
     *
118
     * @throws IOException
119
     * @throws IOPermissionException
120
     */
121 3
    protected function createTempFile(?string $tmpDir=null, ?int $mode=0666): string
122
    {
123 3
        $tmpDir  = $tmpDir ?? sys_get_temp_dir();
124 3
        $tmpFile = tempnam($tmpDir, 'soluble-jasper');
125 3
        if ($tmpFile === false) {
126
            throw new IOException(sprintf(
127
                'Cannot create temporary file in %s',
128
                $tmpDir
129
            ));
130
        }
131 3
        if (chmod($tmpFile, $mode) === false) {
132
            unlink($tmpFile);
133
            throw new IOPermissionException(sprintf(
134
                'Cannot set file permission of file %s.',
135
                $tmpFile
136
            ));
137
        }
138
139 3
        return $tmpFile;
140
    }
141
142
    /**
143
     * @param string[] $config
144
     */
145 3
    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

145
    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...
146
    {
147 3
        $pdfConfig = new SimplePdfExporterConfiguration($this->runner->getBridgeAdapter());
148
149 3
        return $pdfConfig;
150
    }
151
152 3
    private function getFilledReport(): JasperPrint
153
    {
154 3
        if ($this->jasperPrint === null) {
155 3
            $jasperReport      = $this->runner->compileReport($this->report);
156 3
            $this->jasperPrint = $this->runner->fillReport(
157 3
                                                    $jasperReport,
158 3
                                                    $this->report->getReportParams(),
159 3
                                                    $this->report->getDataSource()
160
            );
161
        }
162
163 3
        return $this->jasperPrint;
164
    }
165
}
166