1 | <?php |
||
12 | class ValidatorService |
||
13 | { |
||
14 | |||
15 | const MODE_STRICT = 'strict'; |
||
16 | const MODE_TRANSITIONAL = 'transitional'; |
||
17 | const MODE_DISABLED = 'false'; |
||
18 | |||
19 | /** |
||
20 | * @var array |
||
21 | */ |
||
22 | private $config; |
||
23 | |||
24 | /** |
||
25 | * @var string |
||
26 | */ |
||
27 | private $schemaContent; |
||
28 | |||
29 | /** |
||
30 | * ValidatorService constructor. |
||
31 | * @param array $config |
||
32 | */ |
||
33 | 4 | public function __construct($config) |
|
37 | |||
38 | /** |
||
39 | * Validates the given xliff content with the configured validation mode |
||
40 | * |
||
41 | * @param string $xliffContent |
||
42 | * @return \LibXMLError[] |
||
43 | * @throws \Symfony\Component\Filesystem\Exception\FileNotFoundException |
||
44 | */ |
||
45 | 5 | public function validate($xliffContent) |
|
46 | { |
||
47 | 5 | $errors = []; |
|
48 | |||
49 | 5 | switch ($this->getValidationMode()) { |
|
50 | 5 | case static::MODE_STRICT: |
|
51 | 1 | $schema = 'xliff-core-1.2-strict.xsd'; |
|
52 | 1 | break; |
|
53 | 5 | case static::MODE_TRANSITIONAL: |
|
54 | 1 | $schema = 'xliff-core-1.2-transitional.xsd'; |
|
55 | 1 | break; |
|
56 | 5 | case static::MODE_DISABLED: |
|
57 | default: |
||
58 | 5 | $schema = null; |
|
59 | 5 | break; |
|
60 | } |
||
61 | |||
62 | 5 | if ($schema === null) { |
|
63 | 5 | return $errors; |
|
64 | } |
||
65 | |||
66 | // retrieve schema (from file or previous validation calls) |
||
67 | 1 | $this->schemaContent = $this->schemaContent ?: file_get_contents(__DIR__ . '/../Resources/schema/' . $schema); |
|
68 | 1 | if ($this->schemaContent === null) { |
|
69 | throw new FileNotFoundException('Schema could not be loaded!'); |
||
70 | } |
||
71 | |||
72 | // validate xliff against schema |
||
73 | 1 | libxml_use_internal_errors(true); |
|
74 | 1 | $xmlDOM = new DOMDocument(); |
|
75 | 1 | $xmlDOM->loadXML($xliffContent); |
|
76 | 1 | if (!$xmlDOM->schemaValidateSource($this->schemaContent)) { |
|
77 | 1 | $errors = libxml_get_errors(); |
|
78 | 1 | libxml_clear_errors(); |
|
79 | } |
||
80 | |||
81 | // free up some memory |
||
82 | 1 | unset($xmlDOM); |
|
83 | |||
84 | 1 | return $errors; |
|
85 | } |
||
86 | /** |
||
87 | * Return the configured validation mode |
||
88 | * |
||
89 | * @return mixed |
||
90 | */ |
||
91 | 5 | private function getValidationMode() |
|
95 | } |