Completed
Push — master ( f11c06...b3b38a )
by Sébastien
05:33
created

PDFExporter::getFilledReport()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

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

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