PDF::loadView()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 4
crap 1
1
<?php
2
3
namespace MathieuTu\PDFLayer;
4
5
use GuzzleHttp\Client;
6
use Illuminate\Support\Str;
7
use Illuminate\Http\Response;
8
use Illuminate\Filesystem\Filesystem;
9
use MathieuTu\PDFLayer\Exceptions\PDFLayerException;
10
use Illuminate\Contracts\View\Factory as ViewFactory;
11
use Illuminate\Contracts\Config\Repository as ConfigRepository;
12
13
class PDF
14
{
15
    private $httpClient;
16
    private $view;
17
    private $files;
18
    private $config;
19
    private $params;
20
    private $pdf;
21
22 14
    public function __construct(Client $httpClient, ConfigRepository $config, Filesystem $files, ViewFactory $view)
23
    {
24 14
        $this->httpClient = $httpClient;
25 14
        $this->view = $view;
26 14
        $this->files = $files;
27 14
        $this->config = $this->prepareConfig($config);
28 14
        $this->params = $this->prepareParams();
29 14
    }
30
31
    /**
32
     * @param \Illuminate\Contracts\Config\Repository $config
33
     *
34
     * @return array
35
     */
36 14
    private function prepareConfig(ConfigRepository $config)
37
    {
38 14
        return $config->get('pdflayer');
39
    }
40
41
    /**
42
     * @return \Illuminate\Support\Collection
43
     */
44 14
    private function prepareParams()
45
    {
46 14
        $params = collect($this->config['default_params']);
47 14
        if ($this->config['sandbox']) {
48 14
            $params['test'] = 1;
49
        }
50
51 14
        return $params;
52
    }
53
54
    /**
55
     * Load HTML and encoding from an URL.
56
     *
57
     * @param $url
58
     *
59
     * @return $this
60
     */
61 1
    public function loadUrl($url)
62
    {
63 1
        $this->params['document_url'] = urlencode($url);
64
65 1
        if (!empty($this->config['secret_keyword'])) {
66 1
            $this->params['secret_key'] = md5($url . $this->config['secret_keyword']);
67
        }
68
69 1
        return $this;
70
    }
71
72
    /**
73
     * Load a View and convert it to HTML.
74
     *
75
     * @param string $view
76
     * @param array  $data
77
     * @param array  $mergeData
78
     * @param string $encoding
79
     *
80
     * @return $this
81
     */
82 1
    public function loadView($view, $data = [], $mergeData = [], $encoding = null)
83
    {
84 1
        $html = $this->view->make($view, $data, $mergeData)->render();
85
86 1
        return $this->loadHTML($html, $encoding);
87
    }
88
89
    /**
90
     * Load a HTML string.
91
     *
92
     * @param string $html
93
     * @param string $encoding
94
     *
95
     * @return $this
96
     */
97 3
    public function loadHTML($html, $encoding = null)
98
    {
99 3
        $this->params['document_html'] = $html;
100
101 3
        if ($encoding) {
102 2
            $this->params['text_encoding'] = $encoding;
103
        }
104
105 3
        return $this;
106
    }
107
108
    /**
109
     * Load a HTML file.
110
     *
111
     * @param string $file
112
     */
113 1
    public function loadFile($file)
114
    {
115 1
        $html = file_get_contents($file);
116 1
        $encoding = null;
117 1
        if (isset($http_response_header)) {
118 1
            foreach ($http_response_header as $_header) {
119 1
                if (preg_match("@Content-Type:\s*[\w/]+;\s*?charset=([\S]+)@i", $_header, $matches)) {
120 1
                    $encoding = strtoupper($matches[1]);
121 1
                    break;
122
                }
123
            }
124
        }
125 1
        $this->loadHTML($html, $encoding);
126 1
    }
127
128
    /**
129
     * Set the paper size and orientation.
130
     *
131
     * @param string $layout
132
     * @param string $orientation
133
     *
134
     * @return $this
135
     */
136 1
    public function setPaper($layout, $orientation = 'portrait')
137
    {
138 1
        $this->params['page_size'] = $layout;
139 1
        $this->params['orientation'] = $orientation;
140
141 1
        return $this;
142
    }
143
144
    /**
145
     * Return a response with the PDF to show in the browser.
146
     *
147
     * @param string $filename
148
     *
149
     * @throws \InvalidArgumentException
150
     *
151
     * @return \Illuminate\Http\Response
152
     */
153 1
    public function stream($filename = 'document.pdf')
154
    {
155 1
        return $this->makeResponse($filename, 'inline');
156
    }
157
158
    /**
159
     * @param string $filename
160
     * @param string $contentDisposition
161
     *
162
     * @throws \InvalidArgumentException
163
     *
164
     * @return \Illuminate\Http\Response
165
     */
166 2
    private function makeResponse($filename, $contentDisposition)
167
    {
168 2
        return new Response($this->output(), 200, [
169 2
            'Content-Type'        => 'application/pdf',
170 2
            'Content-Disposition' => $contentDisposition . '; filename="' . $filename . '"',
171
        ]);
172
    }
173
174
    /**
175
     * Output the PDF as a string.
176
     *
177
     * @throws \Exception
178
     *
179
     * @return string The rendered PDF as string
180
     */
181 4
    public function output()
182
    {
183 4
        if (!$this->pdf) {
184 4
            $this->render();
185
        }
186
187 4
        return $this->pdf;
188
    }
189
190
    /**
191
     * @throws \Exception
192
     */
193 4
    private function render()
194
    {
195 4
        list($uri, $postParams) = $this->prepareRequest();
196 4
        $this->pdf = $this->doRequest($uri, $postParams);
197 4
    }
198
199
    /**
200
     * @return array
201
     */
202 12
    private function prepareRequest()
203
    {
204 12
        $uri = $this->config['endpoint'] . '?access_key=' . $this->config['access_key'];
205
206 12
        $postKeys = ['document_html', 'header_html'];
207 12
        $getParams = $this->params->except($postKeys)->toArray();
208
209 12
        $uri .= '&' . http_build_query($getParams);
210 12
        $postParams = $this->params->diff($getParams)->toArray();
211
212 12
        return [$uri, $postParams];
213
    }
214
215
    /**
216
     * @param $uri
217
     * @param $postParams
218
     *
219
     * @throws \RuntimeException
220
     * @throws \MathieuTu\PDFLayer\Exceptions\PDFLayerException
221
     *
222
     * @return string
223
     */
224 4
    private function doRequest($uri, $postParams)
225
    {
226 4
        $response = $this->httpClient->post($uri, [
227 4
            'form_params' => $postParams,
228
        ]);
229
230 4
        $content = $response->getBody()->getContents();
231
232 4
        $error = json_decode($content);
233 4
        if (is_object($error)) {
234 1
            throw new PDFLayerException($error);
235
        }
236
237 4
        return $content;
238
    }
239
240
    /**
241
     * Make the PDF downloadable by the user.
242
     *
243
     * @param string $filename
244
     *
245
     * @throws \InvalidArgumentException
246
     * @throws \Exception
247
     *
248
     * @return \Illuminate\Http\Response
249
     */
250 1
    public function download($filename = 'document.pdf')
251
    {
252 1
        return $this->makeResponse($filename, 'attachment');
253
    }
254
255
    /**
256
     * Save the PDF to a file.
257
     *
258
     * @param $filename
259
     *
260
     * @return $this
261
     */
262 1
    public function save($filename)
263
    {
264 1
        $this->files->put($filename, $this->output());
265
266 1
        return $this;
267
    }
268
269
    /**
270
     * @param $name
271
     * @param $arguments
272
     *
273
     * @throws \InvalidArgumentException
274
     * @throws \BadMethodCallException
275
     *
276
     * @return $this
277
     */
278 1
    public function __call($name, $arguments)
279
    {
280 1
        if (Str::startsWith($name, 'set')) {
281 1
            $propertyCamel = Str::substr($name, Str::length('set'));
282 1
            $property = Str::snake($propertyCamel);
283
284 1
            $this->params[$property] = $arguments[0];
285
286 1
            return $this;
287
        }
288
289 1
        throw new \BadMethodCallException('Call to undefined method ' . static::class . '::' . $name . '()');
290
    }
291
292
    /**
293
     * @param $name
294
     * @param $value
295
     *
296
     * @return mixed
297
     */
298 1
    public function __set($name, $value)
299
    {
300 1
        return $this->params[$name] = $value;
301
    }
302
303
    /**
304
     * Add some parameters.
305
     *
306
     * @param array $params
307
     *
308
     * @return $this
309
     */
310 1
    public function addParams(array $params)
311
    {
312 1
        return $this->setParams($params);
313
    }
314
315
    /**
316
     * Add/Replace some parameters.
317
     *
318
     * @param array $params
319
     * @param bool  $replace
320
     *
321
     * @return $this
322
     */
323 2
    public function setParams(array $params, $replace = false)
324
    {
325 2
        if ($replace) {
326 1
            $this->params = collect($params);
327
        } else {
328 2
            $this->params = $this->params->merge($params);
329
        }
330
331 2
        return $this;
332
    }
333
334
    /**
335
     * Replace some parameters.
336
     *
337
     * @param array $params
338
     *
339
     * @return $this
340
     */
341 1
    public function replaceParams(array $params)
342
    {
343 1
        return $this->setParams($params, true);
344
    }
345
346
    /**
347
     * See all the current parameters.
348
     *
349
     * @return array
350
     */
351 1
    public function seeParams()
352
    {
353 1
        return $this->params->toArray();
354
    }
355
356
    /**
357
     * See the arguments which will be sent during the request.
358
     *
359
     * @param string $key
360
     *
361
     * @return array
362
     */
363 8
    public function seeRequestArgs($key = null)
364
    {
365 8
        list($uri, $postParams) = $this->prepareRequest();
366
367 8
        if ($key !== null) {
368 1
            return ${$key};
369
        }
370
371 8
        return compact('uri', 'postParams');
372
    }
373
}
374