-
Notifications
You must be signed in to change notification settings - Fork 20
/
Libxml.php
77 lines (70 loc) · 2.31 KB
/
Libxml.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
/*
* FluentDOM
*
* @link https://thomas.weinert.info/FluentDOM/
* @copyright Copyright 2009-2021 FluentDOM Contributors
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*
*/
declare(strict_types=1);
namespace FluentDOM\Loader\Supports {
use FluentDOM\DOM\Document;
use FluentDOM\Exceptions\InvalidSource\TypeFile as InValidFileSource;
use FluentDOM\Exceptions\InvalidSource\TypeString as InvalidStringSource;
use FluentDOM\Exceptions\LoadingError\FileNotLoaded;
use FluentDOM\Loader\Libxml\Errors;
use FluentDOM\Loader\Options;
use FluentDOM\Loader\Supports;
trait Libxml {
use Supports;
/**
* @param array|\Traversable|Options $options
* @return Options
* @throws \InvalidArgumentException
*/
public function getOptions($options): Options {
$result = new Options(
$options,
[
Options::CB_IDENTIFY_STRING_SOURCE => function($source) {
return $this->startsWith($source, '<');
}
]
);
$result[Options::LIBXML_OPTIONS] = (int)$result[Options::LIBXML_OPTIONS];
$result[Options::ENCODING] = empty($result[Options::ENCODING]) ? 'utf-8' : $result[Options::ENCODING];
return $result;
}
/**
* @param string $source
* @param array|\Traversable|Options $options
* @return Document
* @throws InvalidStringSource
* @throws InValidFileSource
* @throws FileNotLoaded
* @throws \Throwable
*/
private function loadXmlDocument(string $source, $options): Document {
return (new Errors())->capture(
function () use ($source, $options): Document {
$settings = $this->getOptions($options);
$settings->isAllowed($sourceType = $settings->getSourceType($source));
$document = new Document();
$document->preserveWhiteSpace = (bool)$settings[Options::PRESERVE_WHITESPACE];
switch ($sourceType) {
case Options::IS_FILE :
if (!$document->load($source, $settings[Options::LIBXML_OPTIONS])) {
throw new FileNotLoaded($source);
}
break;
case Options::IS_STRING :
default :
$document->loadXML($source, $settings[Options::LIBXML_OPTIONS]);
}
return $document;
}
);
}
}
}