ILIAS  trunk Revision v11.0_alpha-3011-gc6b235a2e85
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 Result $result;
27 private bool $xmlErrorState = false;
29 private array $errorStack = [];
30
31 public function __construct(private readonly DataTypeFactory $dataFactory)
32 {
33 $this->result = new Result\Error('No XML parsed, yet');
34 }
35
36 private function beginLogging(): void
37 {
38 if ([] === $this->errorStack) {
39 $this->xmlErrorState = libxml_use_internal_errors(true);
40 libxml_clear_errors();
41 } else {
42 $this->addErrors();
43 }
44
45 $this->errorStack[] = [];
46 }
47
48 private function addErrors(): void
49 {
50 $currentErrors = libxml_get_errors();
51 libxml_clear_errors();
52
53 $level = count($this->errorStack) - 1;
54 $this->errorStack[$level] = array_merge($this->errorStack[$level], $currentErrors);
55 }
56
60 private function endLogging(): array
61 {
62 $this->addErrors();
63
64 $errors = array_pop($this->errorStack);
65
66 if ([] === $this->errorStack) {
67 libxml_use_internal_errors($this->xmlErrorState);
68 }
69
70 return $errors;
71 }
72
73 public function parse(string $xmlString): void
74 {
75 try {
76 $this->beginLogging();
77
79 new SimpleXMLElement($xmlString);
80
81 $this->result = $this->dataFactory->ok($xmlString);
82 $this->endLogging();
83 } catch (Exception) {
84 $this->result = $this->dataFactory->error(implode(
85 "\n",
86 array_map(static function (LibXMLError $error): string {
87 return implode(',', [
88 'level=' . $error->level,
89 'code=' . $error->code,
90 'line=' . $error->line,
91 'col=' . $error->column,
92 'msg=' . trim($error->message)
93 ]);
94 }, $this->endLogging())
95 ));
96 }
97 }
98
99 public function result(): Result
100 {
101 return $this->result;
102 }
103}
Builds data types.
Definition: Factory.php:36
__construct(private readonly DataTypeFactory $dataFactory)
parse(string $xmlString)
A result encapsulates a value or an error and simplifies the handling of those.
Definition: Result.php:29