Failed Conditions
Push — master ( 1e9a7e...f3c113 )
by Sébastien
04:54
created

PDFExporter::getPsr7Response()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 11
nc 2
nop 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 Vanvelthem Sébastien
11
 * @license   MIT
12
 */
13
14
namespace Soluble\Jasper\Exporter\Bridged;
15
16
use Psr\Http\Message\ResponseInterface;
17
use Soluble\Japha\Bridge\Adapter as BridgeAdapter;
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 SplFileInfo;
26
use Zend\Diactoros\Response;
27
use Zend\Diactoros\Stream;
28
29
class PDFExporter
30
{
31
    /**
32
     * @var BridgedReportRunner
33
     */
34
    private $runner;
35
36
    /**
37
     * @var Report
38
     */
39
    private $report;
40
41
    /**
42
     * @var JasperPrint
43
     */
44
    private $jasperPrint;
45
46
    /**
47
     * @var BridgeAdapter
48
     */
49
    private $ba;
50
51
    /**
52
     * @var JRPdfExporter
53
     */
54
    private $exporter;
55
56
    public function __construct(BridgedReportRunner $runner, Report $report)
57
    {
58
        $this->runner   = $runner;
59
        $this->report   = $report;
60
        $this->ba       = $runner->getBridgeAdapter();
61
        $this->exporter = new JRPdfExporter($this->ba);
62
    }
63
64
    /**
65
     * @param string   $outputFile
66
     * @param string[] $pdfConfig
67
     */
68
    public function saveFile(string $outputFile, array $pdfConfig = null): void
69
    {
70
        $jasperPrint = $this->getFilledReport();
71
        $this->exporter->setExporterInput($jasperPrint->getJavaProxiedObject());
72
        $this->exporter->setExporterOutput(new \SplFileInfo($outputFile));
73
        if ($pdfConfig !== null) {
74
            $simplePdfConfig = $this->getPdfExporterConfiguration($pdfConfig);
75
            $this->exporter->setConfiguration($simplePdfConfig);
76
        }
77
        $this->exporter->exportReport();
78
    }
79
80
    /**
81
     * Return a new PSR-7 Response object filled with the PDF content.
82
     *
83
     * @param string[]|null $pdfConfig
84
     *
85
     * @throws IOException
86
     * @throws IOPermissionException
87
     *
88
     */
89
    public function getPsr7Response(array $pdfConfig = null): ResponseInterface
90
    {
91
        $tmpFile = $this->createTempFile();
92
93
        try {
94
            $this->saveFile($tmpFile, $pdfConfig);
95
        } catch (\Throwable $e) {
96
            @unlink($tmpFile);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

96
            /** @scrutinizer ignore-unhandled */ @unlink($tmpFile);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
97
            throw $e;
98
        }
99
100
        $response = new Response();
101
        $response = $response->withBody(new Stream($tmpFile));
102
        $response = $response->withHeader('Content-type', 'application/pdf');
103
104
        if (@unlink($tmpFile) === false) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
105
            // do nothing for now
106
        }
107
108
        return $response;
109
    }
110
111
    /**
112
     * @param null|string $tmpDir if null use sys_get_temp_dir()
113
     * @param int|null    $mode   default to '0666'
114
     * @throws IOException
115
     * @throws IOPermissionException
116
     */
117
    protected function createTempFile(?string $tmpDir=null, ?int $mode=0666): string
118
    {
119
        $tmpDir  = $tmpDir ?? sys_get_temp_dir();
120
        $tmpFile = tempnam($tmpDir, 'soluble-jasper');
121
        if ($tmpFile === false) {
122
            throw new IOException(sprintf(
123
                'Cannot create temporary file in %s',
124
                $tmpDir
125
            ));
126
        }
127
        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
        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->ba);
144
145
        return $pdfConfig;
146
    }
147
148
    private function getFilledReport(): JasperPrint
149
    {
150
        if ($this->jasperPrint === null) {
151
            $jasperReport      = $this->runner->compileReport($this->report);
152
            $this->jasperPrint = $this->runner->fillReport(
153
                                                    $jasperReport,
154
                                                    $this->report->getReportParams(),
155
                                                    $this->report->getDataSource()
156
            );
157
        }
158
159
        return $this->jasperPrint;
160
    }
161
}
162