MediaWiki master
XmlLoader.php
Go to the documentation of this file.
1<?php
6
7namespace Wikimedia\Leximorph\Util;
8
9use DOMDocument;
10use Psr\Log\LoggerInterface;
11
21class XmlLoader {
22
28 public function __construct(
29 private readonly LoggerInterface $logger,
30 ) {
31 }
32
43 public function load( string $filePath, string $context = '', bool $allowMissing = false ): ?DOMDocument {
44 // Use file_get_contents instead of DOMDocument::load (T58439)
45 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
46 $xml = @file_get_contents( $filePath );
47 if ( !$xml ) {
48 if ( !$allowMissing ) {
49 $this->logger->error(
50 'Unable to read XML file {filePath} for {context}',
51 [
52 'filePath' => $filePath,
53 'context' => $context,
54 ]
55 );
56 }
57
58 return null;
59 }
60
61 $doc = new DOMDocument();
62 libxml_use_internal_errors( true );
63 if ( !$doc->loadXML( $xml ) ) {
64 $this->logger->error(
65 'Invalid XML format in {filePath} for {context}',
66 [
67 'filePath' => $filePath,
68 'context' => $context,
69 ]
70 );
71 libxml_clear_errors();
72
73 return null;
74 }
75 libxml_clear_errors();
76
77 return $doc;
78 }
79}
load(string $filePath, string $context='', bool $allowMissing=false)
Loads an XML file into a DOMDocument instance.
Definition XmlLoader.php:43
__construct(private readonly LoggerInterface $logger,)
Initializes the XmlLoader with a logger.
Definition XmlLoader.php:28