ILIAS  trunk Revision v11.0_alpha-3011-gc6b235a2e85
class.ilScormImportParser.php
Go to the documentation of this file.
1<?php
2
19declare(strict_types=1);
20
21use ILIAS\Data\Factory as DataTypeFactory;
22
24{
25 private bool $xml_error_state = false;
27 private array $error_stack = [];
28 private DataTypeFactory $df;
29
30 public function __construct(DataTypeFactory $data_factory)
31 {
32 $this->df = $data_factory;
33 }
34
35 private function formatError(LibXMLError $error): string
36 {
37 return implode(',', [
38 'level=' . $error->level,
39 'code=' . $error->code,
40 'line=' . $error->line,
41 'col=' . $error->column,
42 'msg=' . trim($error->message)
43 ]);
44 }
45
46 private function formatErrors(LibXMLError ...$errors): string
47 {
48 $text = '';
49 foreach ($errors as $error) {
50 $text .= $this->formatError($error) . "\n";
51 }
52
53 return $text;
54 }
55
56 private function beginLogging(): void
57 {
58 if ([] === $this->error_stack) {
59 $this->xml_error_state = libxml_use_internal_errors(true);
60 libxml_clear_errors();
61 } else {
62 $this->addErrors();
63 }
64
65 $this->error_stack[] = [];
66 }
67
68 private function addErrors(): void
69 {
70 $currentErrors = libxml_get_errors();
71 libxml_clear_errors();
72
73 $level = count($this->error_stack) - 1;
74 $this->error_stack[$level] = array_merge($this->error_stack[$level], $currentErrors);
75 }
76
80 private function endLogging(): array
81 {
82 $this->addErrors();
83
84 $errors = array_pop($this->error_stack);
85
86 if ([] === $this->error_stack) {
87 libxml_use_internal_errors($this->xml_error_state);
88 }
89
90 return $errors;
91 }
92
93 public function parse(string $xmlString): \ILIAS\Data\Result
94 {
95 try {
96 $this->beginLogging();
97
98 $xml = new SimpleXMLElement($xmlString);
99
100 $errors = $this->endLogging();
101
102 if ($xml->xpath('//SubType')) {
103 return $this->df->ok($xml);
104 }
105
106 $error = new LibXMLError();
107 $error->level = LIBXML_ERR_FATAL;
108 $error->code = 0;
109 $error->message = 'No "SubType" element found';
110 $error->line = 1;
111 $error->column = 0;
112
113 $errors[] = $error;
114
115 return $this->df->error($this->formatErrors(...$errors));
116 } catch (Throwable $e) {
117 return $this->df->error($this->formatErrors(...$this->endLogging()));
118 }
119 }
120}
Builds data types.
Definition: Factory.php:36
formatError(LibXMLError $error)
__construct(DataTypeFactory $data_factory)
formatErrors(LibXMLError ... $errors)
Interface Observer \BackgroundTasks Contains several chained tasks and infos about them.