PDFExporter   A
last analyzed

Complexity

Total Complexity 15

Size/Duplication

Total Lines 139
Duplicated Lines 0 %

Test Coverage

Coverage 75.47%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 15
eloc 54
c 2
b 0
f 0
dl 0
loc 139
ccs 40
cts 53
cp 0.7547
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getPsr7Response() 0 32 6
A saveFile() 0 10 2
A createTempFile() 0 20 3
A getPdfExporterConfiguration() 0 5 1
A getFilledReport() 0 12 2
A __construct() 0 5 1
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-2019 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
96
            throw $e;
97
        }
98
99 3
        if ($response === null) {
100 1
            $response = new Response();
101
        }
102
103 3
        $response = $response->withBody(new Stream($tmpFile));
104 3
        $response = $response->withHeader('Content-type', 'application/pdf');
105
106 3
        if (@unlink($tmpFile) === false) {
107
            $this->runner->getLogger()->warning(
108
                sprintf(
109
                    "Could not delete temp file '%s' after PSR7 response generation: %s.",
110
                    $tmpFile,
111
                    file_exists($tmpFile) ? 'File exists, cannot unlink' : 'File does not exists'
112
                )
113
            );
114
        }
115
116 3
        return $response;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $response could return the type Psr\Http\Message\MessageInterface which includes types incompatible with the type-hinted return Psr\Http\Message\ResponseInterface. Consider adding an additional type-check to rule them out.
Loading history...
117
    }
118
119
    /**
120
     * @param null|string $tmpDir if null use sys_get_temp_dir()
121
     * @param int         $mode   default to '0666'
122
     *
123
     * @throws IOException
124
     * @throws IOPermissionException
125
     */
126 3
    protected function createTempFile(?string $tmpDir=null, int $mode=0666): string
127
    {
128 3
        $tmpDir  = $tmpDir ?? sys_get_temp_dir();
129 3
        $tmpFile = tempnam($tmpDir, 'soluble-jasper');
130 3
        if ($tmpFile === false) {
131
            throw new IOException(sprintf(
132
                'Cannot create temporary file in %s',
133
                $tmpDir
134
            ));
135
        }
136 3
        if (chmod($tmpFile, $mode) === false) {
137
            unlink($tmpFile);
138
139
            throw new IOPermissionException(sprintf(
140
                'Cannot set file permission of file %s.',
141
                $tmpFile
142
            ));
143
        }
144
145 3
        return $tmpFile;
146
    }
147
148 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

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