ILIAS  release_8 Revision v8.24
class.ilXmlChecker.php
Go to the documentation of this file.
1<?php
2
19declare(strict_types=1);
20
22use ILIAS\Data\Factory as DataTypeFactory;
23
24final class ilXMLChecker
25{
26 private DataTypeFactory $dataFactory;
27 private Result $result;
28 private bool $xmlErrorState = false;
30 private array $errorStack = [];
31
32 public function __construct(DataTypeFactory $dataFactory)
33 {
34 $this->dataFactory = $dataFactory;
35 $this->result = new Result\Error('No XML parsed, yet');
36 }
37
38 private function beginLogging(): void
39 {
40 if (0 === count($this->errorStack)) {
41 $this->xmlErrorState = libxml_use_internal_errors(true);
42 libxml_clear_errors();
43 } else {
44 $this->addErrors();
45 }
46
47 $this->errorStack[] = [];
48 }
49
50 private function addErrors(): void
51 {
52 $currentErrors = libxml_get_errors();
53 libxml_clear_errors();
54
55 $level = count($this->errorStack) - 1;
56 $this->errorStack[$level] = array_merge($this->errorStack[$level], $currentErrors);
57 }
58
62 private function endLogging(): array
63 {
64 $this->addErrors();
65
66 $errors = array_pop($this->errorStack);
67
68 if (0 === count($this->errorStack)) {
69 libxml_use_internal_errors($this->xmlErrorState);
70 }
71
72 return $errors;
73 }
74
75 public function parse(string $xmlString): void
76 {
77 try {
78 $this->beginLogging();
79
80 $xml = new SimpleXMLElement($xmlString);
81
82 $this->result = $this->dataFactory->ok($xmlString);
83 $this->endLogging();
84 } catch (Exception $e) {
85 $this->result = $this->dataFactory->error(implode(
86 "\n",
87 array_map(static function (LibXMLError $error): string {
88 return implode(',', [
89 'level=' . $error->level,
90 'code=' . $error->code,
91 'line=' . $error->line,
92 'col=' . $error->column,
93 'msg=' . trim($error->message)
94 ]);
95 }, $this->endLogging())
96 ));
97 }
98 }
99
100 public function result(): Result
101 {
102 return $this->result;
103 }
104}
Builds data types.
Definition: Factory.php:21
A result encapsulates a value or an error and simplifies the handling of those.
Definition: Error.php:18
__construct(DataTypeFactory $dataFactory)
parse(string $xmlString)
DataTypeFactory $dataFactory
$errors
Definition: imgupload.php:65
A result encapsulates a value or an error and simplifies the handling of those.
Definition: Result.php:15
$xml
Definition: metadata.php:351