|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Psr7Unitesting\Html; |
|
4
|
|
|
|
|
5
|
|
|
use Psr7Unitesting\Utils\AbstractConstraint as Constraint; |
|
6
|
|
|
use Symfony\Component\Process\Process; |
|
7
|
|
|
use GuzzleHttp\Client; |
|
8
|
|
|
use GuzzleHttp\Psr7\Request; |
|
9
|
|
|
|
|
10
|
|
|
class IsValid extends Constraint |
|
11
|
|
|
{ |
|
12
|
|
|
const METHOD_REST = 1; |
|
13
|
|
|
const METHOD_CLI = 2; |
|
14
|
|
|
const BIN_FILE = '/vnu.16.3.3/vnu.jar'; |
|
15
|
|
|
|
|
16
|
|
|
public static $method = 2; |
|
17
|
|
|
private $errors = []; |
|
18
|
|
|
|
|
19
|
|
|
public function toString() |
|
20
|
|
|
{ |
|
21
|
|
|
return 'is valid HTML'; |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
protected function matches($html) |
|
25
|
|
|
{ |
|
26
|
|
|
if (self::$method === static::METHOD_CLI) { |
|
27
|
|
|
$result = $this->validateCLI($html); |
|
28
|
|
|
} elseif (self::$method === static::METHOD_REST) { |
|
29
|
|
|
$result = $this->validateREST($html); |
|
30
|
|
|
} else { |
|
31
|
|
|
throw new RuntimeException('Invalid validation method'); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
$this->errors = array_filter($result['messages'], function ($message) { |
|
35
|
|
|
return $message['type'] === 'error'; |
|
36
|
|
|
}); |
|
37
|
|
|
|
|
38
|
|
|
return empty($this->errors); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* Execute the validation through the command line. |
|
43
|
|
|
*/ |
|
44
|
|
|
private static function validateCLI($html) |
|
45
|
|
|
{ |
|
46
|
|
|
$vnu = __DIR__.'/../../bins/'.self::BIN_FILE; |
|
47
|
|
|
|
|
48
|
|
|
$process = new Process("java -jar {$vnu} --format json - ", null, null, $html); |
|
49
|
|
|
|
|
50
|
|
|
$process->run(); |
|
51
|
|
|
|
|
52
|
|
|
$output = $process->getOutput() ?: $process->getErrorOutput(); |
|
53
|
|
|
|
|
54
|
|
|
return json_decode((string) $output, true); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
/** |
|
58
|
|
|
* Execute the validation through the api. |
|
59
|
|
|
*/ |
|
60
|
|
|
private static function validateREST($html) |
|
61
|
|
|
{ |
|
62
|
|
|
$request = new Request('POST', 'https://validator.w3.org/nu/?out=json', ['Content-Type' => 'text/html; charset=utf-8'], $html); |
|
63
|
|
|
$client = new Client(); |
|
64
|
|
|
|
|
65
|
|
|
$response = $client->send($request); |
|
66
|
|
|
|
|
67
|
|
|
return json_decode((string) $response->getBody(), true); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
protected function additionalFailureDescription($html) |
|
71
|
|
|
{ |
|
72
|
|
|
return sprintf('%d errors found: %s', count($this->errors), print_r(array_values($this->errors), true)); |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
|