Completed
Push — develop ( 4a07e0...cb1be4 )
by Barry
11:15
created

Pdfcrowd::setRequestFactory()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Swis\PdfcrowdClient;
6
7
use CURLFile;
8
use Swis\PdfcrowdClient\Exceptions\PdfcrowdException;
9
use Swis\PdfcrowdClient\Http\FactoryInterface;
10
use Swis\PdfcrowdClient\Http\RequestFactory;
11
use Swis\PdfcrowdClient\Http\RequestInterface;
12
13
class Pdfcrowd
14
{
15
    /** @var array */
16
    private $fields;
17
18
    /** @var string */
19
    private $scheme;
20
21
    /** @var int */
22
    private $port;
23
24
    /** @var string */
25
    private $api_prefix;
26
27
    /** @var int */
28
    private $curlopt_timeout;
29
30
    /** @var string */
31
    private $hostname;
32
33
    /** @var string */
34
    private $user_agent;
35
36
    /** @var int */
37
    private $num_tokens_before;
38
39
    /** @var int */
40
    private $http_code;
41
42
    /** @var string */
43
    private $error;
44
45
    private $outstream;
46
47
    /** @var FactoryInterface */
48
    protected $requestFactory;
49
50
    /* @var RequestInterface */
51
    private $request;
52
53
    /** @var bool  */
54
    private $track_tokens = false;
55
56
    public static $client_version = '2.7';
57
    public static $http_port = 80;
58
    public static $https_port = 443;
59
    public static $api_host = 'pdfcrowd.com';
60
61
    private $proxy_name = null;
62
    private $proxy_port = null;
63
    private $proxy_username = '';
64
    private $proxy_password = '';
65
66
    const SINGLE_PAGE = 1;
67
    const CONTINUOUS = 2;
68
    const CONTINUOUS_FACING = 3;
69
70
    const NONE_VISIBLE = 1;
71
    const THUMBNAILS_VISIBLE = 2;
72
    const FULLSCREEN = 3;
73
74
    const FIT_WIDTH = 1;
75
    const FIT_HEIGHT = 2;
76
    const FIT_PAGE = 3;
77
78
    /**
79
     * Pdfcrowd constructor.
80
     *
81
     * @param string $username
82
     * @param string $key
83
     */
84
    public function __construct(string $username, string $key)
85
    {
86
        $this->hostname = self::$api_host;
87
88
        $this->useSSL(true);
89
90
        $this->fields = [
91
            'username' => $username,
92
            'key' => $key,
93
            'pdf_scaling_factor' => 1,
94
            'html_zoom' => 200,
95
        ];
96
97
        $this->user_agent = 'pdfcrowd_php_client_'.self::$client_version.'_(http://pdfcrowd.com)';
98
99
        $this->requestFactory = new RequestFactory();
100
    }
101
102
    /**
103
     * This method allows you to override the default CurlRequest object. Added for testing purposes.
104
     *
105
     * @param \Swis\PdfcrowdClient\Http\FactoryInterface $requestFactory
106
     */
107
    public function setRequestFactory(FactoryInterface $requestFactory)
108
    {
109
        $this->requestFactory = $requestFactory;
110
    }
111
112
    /**
113
     * Each httpPost-call uses a clean request object.
114
     *
115
     * @return \Swis\PdfcrowdClient\Http\RequestInterface
116
     * @throws \Swis\PdfcrowdClient\Exceptions\PdfcrowdException
117
     */
118
    protected function getNewRequestObject(): RequestInterface
119
    {
120
        $request = $this->requestFactory->create();
121
122
        if (!$request instanceof RequestInterface) {
123
            throw new PdfcrowdException('Request object must extend the RequestInterface');
124
        }
125
126
        return $request;
127
    }
128
129
    /**
130
     * Converts an in-memory html document.
131
     *
132
     * @param string $src       a string containing a html document
133
     * @param null   $outstream output stream, if null then the return value is a string containing the PDF
134
     *
135
     * @return mixed
136
     * @throws \Swis\PdfcrowdClient\Exceptions\PdfcrowdException
137
     */
138
    public function convertHtml($src, $outstream = null)
139
    {
140
        if (!$src) {
141
            throw new PdfcrowdException('convertHTML(): the src parameter must not be empty');
142
        }
143
144
        $this->fields['src'] = $src;
145
        $uri = $this->api_prefix.'/pdf/convert/html/';
146
        $postfields = http_build_query($this->fields, '', '&');
147
148
        if ($this->track_tokens) {
149
            $this->num_tokens_before = $this->numTokens();
150
        }
151
152
        return $this->httpPost($uri, $postfields, $outstream);
153
    }
154
155
    /**
156
     * Converts an in-memory html document.
157
     *
158
     * @param string $src       a path to an html file
159
     * @param null   $outstream output stream, if null then the return value is a string containing the PDF
160
     *
161
     * @return mixed
162
     * @throws \Swis\PdfcrowdClient\Exceptions\PdfcrowdException
163
     */
164
    public function convertFile(string $src, $outstream = null)
165
    {
166
        $src = trim($src);
167
168
        if (!file_exists($src)) {
169
            $cwd = getcwd();
170
            throw new PdfcrowdException("convertFile(): '{$src}' not found
171
                        Possible reasons:
172
                         1. The file is missing.
173
                         2. You misspelled the file name.
174
                         3. You use a relative file path (e.g. 'index.html') but the current working
175
                            directory is somewhere else than you expect: '${cwd}'
176
                            Generally, it is safer to use an absolute file path instead of a relative one.
177
                        ");
178
        }
179
180
        if (is_dir($src)) {
181
            throw new PdfcrowdException("convertFile(): '{$src}' must be file, not a directory");
182
        }
183
184
        if (!is_readable($src)) {
185
            throw new PdfcrowdException(
186
                "convertFile(): cannot read '{$src}', please check if the process has sufficient permissions"
187
            );
188
        }
189
190
        if (!filesize($src)) {
191
            throw new PdfcrowdException("convertFile(): '{$src}' must not be empty");
192
        }
193
194
        if (version_compare(PHP_VERSION, '5.5.0') >= 0) {
195
            $this->fields['src'] = new CurlFile($src);
196
        } else {
197
            $this->fields['src'] = '@'.$src;
198
        }
199
200
        $uri = $this->api_prefix.'/pdf/convert/html/';
201
202
        if ($this->track_tokens) {
203
            $this->num_tokens_before = $this->numTokens();
204
        }
205
206
        return $this->httpPost($uri, $this->fields, $outstream);
207
    }
208
209
    /**
210
     * Converts a web page.
211
     *
212
     * @param string $src       a web page URL
213
     * @param null   $outstream output stream, if null then the return value is a string containing the PDF
214
     *
215
     * @return mixed
216
     * @throws \Swis\PdfcrowdClient\Exceptions\PdfcrowdException
217
     */
218
    public function convertURI(string $src, $outstream = null)
219
    {
220
        $src = trim($src);
221
        if (!preg_match("/^https?:\/\/.*/i", $src)) {
222
            throw new PdfcrowdException("convertURI(): the URL must start with http:// or https:// (got '$src')");
223
        }
224
225
        $this->fields['src'] = $src;
226
        $uri = $this->api_prefix.'/pdf/convert/uri/';
227
        $postfields = http_build_query($this->fields, '', '&');
228
229
        if ($this->track_tokens) {
230
            $this->num_tokens_before = $this->numTokens();
231
        }
232
233
        return $this->httpPost($uri, $postfields, $outstream);
234
    }
235
236
    /**
237
     * Returns the number of available conversion tokens.
238
     *
239
     * @return int
240
     */
241
    public function numTokens(): int
242
    {
243
        $username = $this->fields['username'];
244
        $uri = $this->api_prefix."/user/{$username}/tokens/";
245
        $arr = ['username' => $this->fields['username'],
246
                'key' => $this->fields['key'], ];
247
        $postfields = http_build_query($arr, '', '&');
248
        $ntokens = $this->httpPost($uri, $postfields, null);
249
250
        return (int) $ntokens;
251
    }
252
253
    /**
254
     * Get the number of tokens used in the last conversion.
255
     * This is only possible if you enable tracking tokens using trackTokens(true).
256
     *
257
     * @see trackTokens()
258
     *
259
     * @return int
260
     * @throws \Swis\PdfcrowdClient\Exceptions\PdfcrowdException
261
     */
262
    public function getUsedTokens(): int
263
    {
264
        if (!$this->track_tokens) {
265
            throw new PdfcrowdException('
266
                getUsedTokens only works if you enable tracking tokens with trackTokens(true)
267
            ');
268
        }
269
270
        $num_tokens_after = $this->numTokens();
271
272
        return (int) $this->num_tokens_before - $num_tokens_after;
273
    }
274
275
    /**
276
     * Track how many tokens are available before each request.
277
     * After a request you can ask the number of used tokens with getUsedTokens.
278
     *
279
     * @see getUsedTokens()
280
     *
281
     * @param bool $trackTokens
282
     */
283
    public function trackTokens(bool $trackTokens = true)
284
    {
285
        $this->track_tokens = $trackTokens;
286
    }
287
288
    /**
289
     * Turn SSL on or off.
290
     *
291
     * @param bool $use_ssl
292
     */
293
    public function useSSL(bool $use_ssl)
294
    {
295
        if ($use_ssl) {
296
            $this->port = self::$https_port;
297
            $this->scheme = 'https';
298
        } else {
299
            $this->port = self::$http_port;
300
            $this->scheme = 'http';
301
        }
302
303
        $this->api_prefix = "{$this->scheme}://{$this->hostname}/api";
304
    }
305
306
    public function setPageWidth($value)
307
    {
308
        $this->fields['width'] = $value;
309
    }
310
311
    public function setPageHeight($value)
312
    {
313
        $this->fields['height'] = $value;
314
    }
315
316
    public function setHorizontalMargin($value)
317
    {
318
        $this->fields['margin_right'] = $this->fields['margin_left'] = $value;
319
    }
320
321
    public function setVerticalMargin($value)
322
    {
323
        $this->fields['margin_top'] = $this->fields['margin_bottom'] = $value;
324
    }
325
326
    public function setBottomMargin($value)
327
    {
328
        $this->fields['margin_bottom'] = $value;
329
    }
330
331
    public function setPageMargins($top, $right, $bottom, $left)
332
    {
333
        $this->fields['margin_top'] = $top;
334
        $this->fields['margin_right'] = $right;
335
        $this->fields['margin_bottom'] = $bottom;
336
        $this->fields['margin_left'] = $left;
337
    }
338
339
    /**
340
     * If value is set to True then the PDF is encrypted. This prevents search engines from indexing the document.
341
     * The default is False.
342
     *
343
     * @param bool $val
344
     */
345
    public function setEncrypted(bool $val = true)
346
    {
347
        $this->setOrUnset($val, 'encrypted');
348
    }
349
350
    /**
351
     * Protects the PDF with a user password. When a PDF has a user password, it must be supplied in order to view the
352
     * document and to perform operations allowed by the access permissions. At most 32 characters.
353
     *
354
     * @param string $pwd
355
     */
356
    public function setUserPassword(string $pwd)
357
    {
358
        $this->setOrUnset($pwd, 'user_pwd');
359
    }
360
361
    /**
362
     * Protects the PDF with an owner password. Supplying an owner password grants unlimited access to the PDF
363
     * including changing the passwords and access permissions. At most 32 characters.
364
     *
365
     * @param string $pwd
366
     */
367
    public function setOwnerPassword(string $pwd)
368
    {
369
        $this->setOrUnset($pwd, 'owner_pwd');
370
    }
371
372
    /**
373
     * Set value to True disables printing the generated PDF. The default is False.
374
     *
375
     * @param bool $val
376
     */
377
    public function setNoPrint(bool $val = true)
378
    {
379
        $this->setOrUnset($val, 'no_print');
380
    }
381
382
    /**
383
     * Set value to True to disable modifying the PDF. The default is False.
384
     *
385
     * @param bool $val
386
     */
387
    public function setNoModify(bool $val = true)
388
    {
389
        $this->setOrUnset($val, 'no_modify');
390
    }
391
392
    /**
393
     * Set value to True to disable extracting text and graphics from the PDF. The default is False.
394
     *
395
     * @param bool $val
396
     */
397
    public function setNoCopy(bool $val = true)
398
    {
399
        $this->setOrUnset($val, 'no_copy');
400
    }
401
402
    /**
403
     * Specifies the initial page layout when the PDF is opened in a viewer.
404
     *
405
     * Possible values:
406
     *   \Swis\PdfcrowdClient\Pdfcrowd::SINGLE_PAGE
407
     *   \Swis\PdfcrowdClient\Pdfcrowd::CONTINUOUS
408
     *   \Swis\PdfcrowdClient\Pdfcrowd::CONTINUOUS_FACING
409
     *
410
     * @param int $value
411
     */
412
    public function setPageLayout(int $value)
413
    {
414
        assert($value > 0 && $value <= 3);
415
        $this->fields['page_layout'] = $value;
416
    }
417
418
    /**
419
     * Specifies the appearance of the PDF when opened.
420
     *
421
     * Possible values:
422
     *   \Swis\PdfcrowdClient\Pdfcrowd::NONE_VISIBLE
423
     *   \Swis\PdfcrowdClient\Pdfcrowd::THUMBNAILS_VISIBLE
424
     *   \Swis\PdfcrowdClient\Pdfcrowd::FULLSCREEN
425
     *
426
     * @param int $value
427
     */
428
    public function setPageMode(int $value)
429
    {
430
        assert($value > 0 && $value <= 3);
431
        $this->fields['page_mode'] = $value;
432
    }
433
434
    /**
435
     * @param string $value
436
     */
437
    public function setFooterText(string $value)
438
    {
439
        $this->setOrUnset($value, 'footer_text');
440
    }
441
442
    /**
443
     * Set value to False to disable printing images to the PDF. The default is True.
444
     *
445
     * @param bool $value
446
     */
447
    public function enableImages(bool $value = true)
448
    {
449
        $this->setOrUnset(!$value, 'no_images');
450
    }
451
452
    /**
453
     * Set value to False to disable printing backgrounds to the PDF. The default is True.
454
     *
455
     * @param bool $value
456
     */
457
    public function enableBackgrounds(bool $value = true)
458
    {
459
        $this->setOrUnset(!$value, 'no_backgrounds');
460
    }
461
462
    /**
463
     * Set HTML zoom in percents. It determines the precision used for rendering of the HTML content. Despite its name,
464
     * it does not zoom the HTML content. Higher values can improve glyph positioning and can lead to overall better
465
     * visual appearance of generated PDF .The default value is 200.
466
     *
467
     * @see setPdfScalingFactor
468
     *
469
     * @param int $value
470
     */
471
    public function setHtmlZoom(int $value)
472
    {
473
        $this->setOrUnset($value, 'html_zoom');
474
    }
475
476
    /**
477
     * Set value to False to disable JavaScript in web pages. The default is True.
478
     *
479
     * @param bool $value
480
     */
481
    public function enableJavaScript(bool $value = true)
482
    {
483
        $this->setOrUnset(!$value, 'no_javascript');
484
    }
485
486
    /**
487
     * Set value to False to disable hyperlinks in the PDF. The default is True.
488
     *
489
     * @param bool $value
490
     */
491
    public function enableHyperlinks(bool $value = true)
492
    {
493
        $this->setOrUnset(!$value, 'no_hyperlinks');
494
    }
495
496
    /**
497
     * Value is the text encoding used when none is specified in a web page. The default is utf-8.
498
     *
499
     * @param string $value
500
     */
501
    public function setDefaultTextEncoding(string $value)
502
    {
503
        $this->setOrUnset($value, 'text_encoding');
504
    }
505
506
    /**
507
     * If value is True then the print CSS media type is used (if available).
508
     *
509
     * @param bool $value
510
     */
511
    public function usePrintMedia(bool $value = true)
512
    {
513
        $this->setOrUnset($value, 'use_print_media');
514
    }
515
516
    /**
517
     * Prints at most npages pages.
518
     *
519
     * @param int $value
520
     */
521
    public function setMaxPages(int $value)
522
    {
523
        $this->fields['max_pages'] = $value;
524
    }
525
526
    /**
527
     * @param bool $value
528
     */
529
    public function enablePdfcrowdLogo(bool $value = true)
530
    {
531
        $this->setOrUnset($value, 'pdfcrowd_logo');
532
    }
533
534
    /**
535
     * value specifies the appearance of the PDF when opened.
536
     *
537
     * Possible values:
538
     *   \Swis\Pdfcrowd\Pdfcrowd::FIT_WIDTH
539
     *   \Swis\Pdfcrowd\Pdfcrowd::FIT_HEIGHT
540
     *   \Swis\Pdfcrowd\Pdfcrowd::FIT_PAGE
541
     *
542
     * @param int $value
543
     */
544
    public function setInitialPdfZoomType(int $value)
545
    {
546
        assert($value > 0 && $value <= 3);
547
        $this->fields['initial_pdf_zoom_type'] = $value;
548
    }
549
550
    /**
551
     * value specifies the initial page zoom of the PDF when opened.
552
     *
553
     * @param $value
554
     */
555
    public function setInitialPdfExactZoom($value)
556
    {
557
        $this->fields['initial_pdf_zoom_type'] = 4;
558
        $this->fields['initial_pdf_zoom'] = $value;
559
    }
560
561
    /**
562
     * The scaling factor used to convert between HTML and PDF. The default value is 1.0.
563
     *
564
     * @param float $value
565
     */
566
    public function setPdfScalingFactor(float $value)
567
    {
568
        $this->fields['pdf_scaling_factor'] = $value;
569
    }
570
571
    /**
572
     * Sets the author field in the created PDF.
573
     *
574
     * @param string $value
575
     */
576
    public function setAuthor(string $value)
577
    {
578
        $this->fields['author'] = $value;
579
    }
580
581
    /**
582
     * If value is True then the conversion will fail when the source URI returns 4xx or 5xx HTTP status code. The
583
     * default is False.
584
     *
585
     * @param bool $value
586
     */
587
    public function setFailOnNon200(bool $value)
588
    {
589
        $this->fields['fail_on_non200'] = $value;
590
    }
591
592
    /**
593
     * Places the specified html code inside the page footer. The following variables are expanded:
594
     *   %u - URL to convert.
595
     *   %p - The current page number.
596
     *   %n - Total number of pages.
597
     *
598
     * @param string $value
599
     */
600
    public function setFooterHtml(string $value)
601
    {
602
        $this->fields['footer_html'] = $value;
603
    }
604
605
    /**
606
     * Loads HTML code from the specified url and places it inside the page footer. See setFooterHtml for the list of
607
     * variables that are expanded.
608
     *
609
     * @see setFooterHtml
610
     *
611
     * @param string $value
612
     */
613
    public function setFooterUrl(string $value)
614
    {
615
        $this->fields['footer_url'] = $value;
616
    }
617
618
    /**
619
     * Places the specified html code inside the page header. See setFooterHtml for the list of variables that are
620
     * expanded.
621
     *
622
     * @see setFooterHtml
623
     *
624
     * @param string $value
625
     */
626
    public function setHeaderHtml(string $value)
627
    {
628
        $this->fields['header_html'] = $value;
629
    }
630
631
    /**
632
     * Loads HTML code from the specified url and places it inside the page header. See setFooterHtml for the list of
633
     * variables that are expanded.
634
     *
635
     * @see setFooterHtml
636
     *
637
     * @param string $value
638
     */
639
    public function setHeaderUrl(string $value)
640
    {
641
        $this->fields['header_url'] = $value;
642
    }
643
644
    /**
645
     * The page background color in RRGGBB hexadecimal format.
646
     *
647
     * @param string $value
648
     */
649
    public function setPageBackgroundColor(string $value)
650
    {
651
        $this->fields['page_background_color'] = $value;
652
    }
653
654
    /**
655
     * Does not print the body background. Requires the following CSS rule to be declared:
656
     *   body {background-color:rgba(255,255,255,0.0);}
657
     *
658
     * @param bool $value
659
     */
660
    public function setTransparentBackground(bool $value = true)
661
    {
662
        $this->setOrUnset($value, 'transparent_background');
663
    }
664
665
    /**
666
     * An offset between physical and logical page numbers. The default value is 0.
667
     *
668
     * @example if set to "1" then the page numbering will start with 1 on the second page.
669
     *
670
     * @param int $value
671
     */
672
    public function setPageNumberingOffset(int $value)
673
    {
674
        $this->fields['page_numbering_offset'] = $value;
675
    }
676
677
    /**
678
     * Value is a comma seperated list of physical page numbers on which the header a footer are not printed. Negative
679
     * numbers count backwards from the last page: -1 is the last page, -2 is the last but one page, and so on.
680
     *
681
     * @example "1,-1" will not print the header and footer on the first and the last page.
682
     *
683
     * @param string $value
684
     */
685
    public function setHeaderFooterPageExcludeList(string $value)
686
    {
687
        $this->fields['header_footer_page_exclude_list'] = $value;
688
    }
689
690
    /**
691
     * url is a public absolute URL of the watermark image (must start either with http:// or https://). The supported
692
     * formats are PNG and JPEG. offset_x and offset_y is the watermark offset in units. The default offset is (0,0).
693
     *
694
     * @param string $url
695
     * @param int    $offset_x
696
     * @param int    $offset_y
697
     */
698
    public function setWatermark(string $url, $offset_x = 0, $offset_y = 0)
699
    {
700
        $this->fields['watermark_url'] = $url;
701
        $this->fields['watermark_offset_x'] = $offset_x;
702
        $this->fields['watermark_offset_y'] = $offset_y;
703
    }
704
705
    /**
706
     * Rotates the watermark by angle degrees.
707
     *
708
     * @param int $angle
709
     */
710
    public function setWatermarkRotationsetWatermarkRotation(int $angle)
711
    {
712
        $this->fields['watermark_rotation'] = $angle;
713
    }
714
715
    /**
716
     * When value is set to True then the watermark is be placed in the background. By default, the watermark is
717
     * placed in the foreground.
718
     *
719
     * @param bool $val
720
     */
721
    public function setWatermarkInBackground(bool $val = true)
722
    {
723
        $this->setOrUnset($val, 'watermark_in_background');
724
    }
725
726
    /**
727
     * @param string $proxyname
728
     * @param int    $port
729
     * @param string $username
730
     * @param string $password
731
     */
732
    public function setProxy(string $proxyname, int $port, string $username = '', string $password = '')
733
    {
734
        $this->proxy_name = $proxyname;
735
        $this->proxy_port = $port;
736
        $this->proxy_username = $username;
737
        $this->proxy_password = $password;
738
    }
739
740
    /**
741
     * @param string $user_agent
742
     */
743
    public function setUserAgent(string $user_agent)
744
    {
745
        $this->user_agent = $user_agent;
746
    }
747
748
    /**
749
     * @param int $timeout
750
     */
751
    public function setTimeout(int $timeout)
752
    {
753
        if (is_int($timeout) && $timeout > 0) {
754
            $this->curlopt_timeout = $timeout;
755
        }
756
    }
757
758
    /**
759
     * @param string $url
760
     * @param        $postfields
761
     * @param        $outstream
762
     *
763
     * @return mixed
764
     * @throws \Swis\PdfcrowdClient\Exceptions\PdfcrowdException
765
     */
766
    private function httpPost(string $url, $postfields, $outstream)
767
    {
768
        $this->request = $this->getNewRequestObject();
769
770
        $this->request->setOption(CURLOPT_URL, $url);
771
        $this->request->setOption(CURLOPT_HEADER, false);
772
        $this->request->setOption(CURLOPT_CONNECTTIMEOUT, 10);
773
        $this->request->setOption(CURLOPT_RETURNTRANSFER, true);
774
        $this->request->setOption(CURLOPT_POST, true);
775
        $this->request->setOption(CURLOPT_PORT, $this->port);
776
        $this->request->setOption(CURLOPT_POSTFIELDS, $postfields);
777
        $this->request->setOption(CURLOPT_DNS_USE_GLOBAL_CACHE, false);
778
        $this->request->setOption(CURLOPT_USERAGENT, $this->user_agent);
779
780
        if (isset($this->curlopt_timeout)) {
781
            $this->request->setOption(CURLOPT_TIMEOUT, $this->curlopt_timeout);
782
        }
783
784
        if ($outstream) {
785
            $this->outstream = $outstream;
786
            $this->request->setOption(CURLOPT_WRITEFUNCTION, [$this, 'receiveToStream']);
787
        }
788
789
        if ($this->scheme == 'https' && self::$api_host == 'pdfcrowd.com') {
790
            $this->request->setOption(CURLOPT_SSL_VERIFYPEER, true);
791
        } else {
792
            $this->request->setOption(CURLOPT_SSL_VERIFYPEER, false);
793
        }
794
795
        if ($this->proxy_name) {
796
            $this->request->setOption(CURLOPT_PROXY, $this->proxy_name.':'.$this->proxy_port);
797
            if ($this->proxy_username) {
798
                $this->request->setOption(CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
799
                $this->request->setOption(CURLOPT_PROXYUSERPWD, $this->proxy_username.':'.$this->proxy_password);
800
            }
801
        }
802
803
        $this->http_code = 0;
804
        $this->error = '';
805
806
        $response = $this->request->execute();
807
        $this->http_code = (int) $this->request->getInfo(CURLINFO_HTTP_CODE);
808
        $error_str = $this->request->getErrorMessage();
809
        $error_nr = (int) $this->request->getErrorNumber();
810
        $this->request->close();
811
812
        if ($error_nr !== 0) {
813
            throw new PdfcrowdException($error_str, $error_nr);
814
        } elseif ($this->http_code === 200) {
815
            if ($outstream === null) {
816
                return $response;
817
            }
818
        }
819
820
        throw new PdfcrowdException($this->error ? $this->error : $response, $this->http_code);
821
    }
822
823
    /**
824
     * @see http://php.net/manual/en/function.curl-setopt.php and look for CURLOPT_WRITEFUNCTION
825
     *
826
     * @param $curl
827
     * @param $data
828
     *
829
     * @return bool|int
830
     * @throws \Swis\PdfcrowdClient\Exceptions\PdfcrowdException
831
     */
832
    private function receiveToStream($curl, $data)
833
    {
834
        if ($this->http_code == 0) {
835
            $this->http_code = (int) curl_getinfo($curl, CURLINFO_HTTP_CODE);
836
        }
837
838
        if ($this->http_code >= 400) {
839
            $this->error = $this->error.$data;
840
841
            return strlen($data);
842
        }
843
844
        $written = fwrite($this->outstream, $data);
845
        if ($written != strlen($data)) {
846
            if (get_magic_quotes_runtime()) {
847
                throw new PdfcrowdException("
848
                    Cannot write the PDF file because the 'magic_quotes_runtime' setting is enabled. Please disable 
849
                    it either in your php.ini file, or in your code by calling 'set_magic_quotes_runtime(false)'.
850
                ");
851
            } else {
852
                throw new PdfcrowdException('Writing the PDF file failed. The disk may be full.');
853
            }
854
        }
855
856
        return $written;
857
    }
858
859
    /**
860
     * Set or unset a parameter that will be sent with the request to the pdfcrowd API.
861
     *
862
     * @param mixed $val
863
     * @param string $field
864
     */
865
    private function setOrUnset($val, string $field)
866
    {
867
        if ($val) {
868
            $this->fields[$field] = $val;
869
        } else {
870
            unset($this->fields[$field]);
871
        }
872
    }
873
}
874