|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Ottosmops\Pdfvalidate; |
|
4
|
|
|
|
|
5
|
|
|
use Ottosmops\Pdfvalidate\Exceptions\FileNotFound; |
|
6
|
|
|
use Ottosmops\Pdfvalidate\Exceptions\BinaryNotFound; |
|
7
|
|
|
use Ottosmops\Pdfvalidate\Exceptions\MimeTypeIsNotPdf; |
|
8
|
|
|
use Symfony\Component\Process\Process; |
|
9
|
|
|
|
|
10
|
|
|
class Validator { |
|
11
|
|
|
|
|
12
|
|
|
public $file; |
|
13
|
|
|
|
|
14
|
|
|
public $error = ''; |
|
15
|
|
|
|
|
16
|
|
|
public $process = ''; |
|
17
|
|
|
|
|
18
|
|
|
public $output; |
|
19
|
|
|
|
|
20
|
|
|
public $executable; |
|
21
|
|
|
|
|
22
|
7 |
|
public function __construct($file, $executable = '') |
|
23
|
|
|
{ |
|
24
|
7 |
|
$this->executable = $executable ? $executable : 'pdftocairo'; |
|
25
|
7 |
|
$this->checkExecutable(); |
|
26
|
6 |
|
if (!is_file($file)) { |
|
27
|
1 |
|
throw new FileNotFound($file); |
|
28
|
|
|
} |
|
29
|
5 |
|
if (!self::is_pdf($file)) { |
|
30
|
1 |
|
throw new MimeTypeIsNotPdf($file); |
|
31
|
|
|
} |
|
32
|
4 |
|
$this->file = $file; |
|
33
|
4 |
|
} |
|
34
|
|
|
|
|
35
|
1 |
|
public static function validate($file, $executable = '') |
|
36
|
|
|
{ |
|
37
|
1 |
|
return (new static($file, $executable)); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
7 |
|
public function checkExecutable() |
|
41
|
|
|
{ |
|
42
|
7 |
|
$process = new Process('which ' . $this->executable); |
|
43
|
7 |
|
$process->run(); |
|
44
|
7 |
|
if (!$process->isSuccessful()) { |
|
45
|
1 |
|
throw new BinaryNotFound($process); |
|
46
|
|
|
} |
|
47
|
6 |
|
return true; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
5 |
|
public static function is_pdf($file) |
|
51
|
|
|
{ |
|
52
|
5 |
|
$finfo = finfo_open(FILEINFO_MIME_TYPE); |
|
53
|
5 |
|
return finfo_file($finfo, $file) == 'application/pdf'; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
4 |
|
public function check() |
|
57
|
|
|
{ |
|
58
|
4 |
|
$command = $this->executable . ' -pdf '. $this->file .' - 2>&1 >/dev/null'; |
|
59
|
|
|
|
|
60
|
4 |
|
$process = new Process($command); |
|
61
|
4 |
|
$process->run(); |
|
62
|
|
|
|
|
63
|
4 |
|
$output = $process->getOutput(); |
|
64
|
|
|
|
|
65
|
4 |
|
if (!$output) { |
|
66
|
2 |
|
return true; |
|
67
|
|
|
}; |
|
68
|
|
|
|
|
69
|
2 |
|
if (mb_strpos($output, 'Error') !== false) { |
|
70
|
2 |
|
$this->error = "Could open the PDF, but the PDF seems to be corrupted."; |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
2 |
|
if (mb_strpos($output, 'Error opening') !== false) { |
|
74
|
1 |
|
$this->error = "Could not open the PDF."; |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
2 |
|
$this->output = $output; |
|
78
|
2 |
|
return false; |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|