1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Copyright (c) 2017–2018 Ryan Parman <http://ryanparman.com>. |
4
|
|
|
* Copyright (c) 2017–2018 Contributors. |
5
|
|
|
* |
6
|
|
|
* http://opensource.org/licenses/Apache2.0 |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
declare(strict_types=1); |
10
|
|
|
|
11
|
|
|
namespace SimplePie\Middleware\Xml; |
12
|
|
|
|
13
|
|
|
use SimplePie\Middleware\AbstractMiddleware; |
14
|
|
|
use SimplePie\Type\Node; |
15
|
|
|
|
16
|
|
|
abstract class AbstractXmlMiddleware extends AbstractMiddleware |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* Replace all instances of `%s` with the `$namespaceAlias` parameter. |
20
|
|
|
* |
21
|
|
|
* This is similar to `sprintf()`, but the `$namespaceAlias` is applied to _all_ instances of `%s`. |
22
|
|
|
* |
23
|
|
|
* @param string $query An XPath query where `%s` is used in-place of the XML namespace alias. |
24
|
|
|
* @param string $namespaceAlias The XML namespace alias to apply. |
25
|
|
|
* |
26
|
|
|
* @return string |
27
|
|
|
*/ |
28
|
|
|
public function applyNsToQuery(string $query, string $namespaceAlias): string |
29
|
|
|
{ |
30
|
|
|
return \str_replace('%s', $namespaceAlias, $query); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Produce an XPath 1.0 expression which is used to query XML document nodes. |
35
|
|
|
* |
36
|
|
|
* @param string $namespaceAlias The XML namespace alias to apply. |
37
|
|
|
* @param string ...$path A variadic parameter which accepts the names of the XML |
38
|
|
|
* tree nodes in sequence. |
39
|
|
|
* |
40
|
|
|
* @return string An XPath 1.0 expression. |
41
|
|
|
* |
42
|
|
|
* @see https://wiki.php.net/rfc/variadics |
43
|
|
|
* @see http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list |
44
|
|
|
*/ |
45
|
|
|
public function generateQuery(string $namespaceAlias, string ...$path): string |
46
|
|
|
{ |
47
|
|
|
$query = ''; |
48
|
|
|
|
49
|
|
|
foreach ($path as $p) { |
50
|
|
|
$query .= \sprintf( |
51
|
|
|
'/%s:*[translate(name(), \'%s\', \'%s\') = \'%s\']', |
52
|
|
|
$namespaceAlias, |
53
|
|
|
'ABCDEFGHIJKLMNOPQRSTUVWXYZ', |
54
|
|
|
'abcdefghijklmnopqrstuvwxyz', |
55
|
|
|
$p |
56
|
|
|
); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
return $query; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* Some elements in the feed should only have one result. This handles those cases. |
64
|
|
|
* |
65
|
|
|
* @param callable $fn A callable which returns a `DOMElementList`. |
66
|
|
|
* |
67
|
|
|
* @return array Returns an array with keys of `text` and `html`. |
68
|
|
|
*/ |
69
|
|
|
public function handleSingleNode(callable $fn): Node |
70
|
|
|
{ |
71
|
|
|
$nodes = $fn(); |
72
|
|
|
|
73
|
|
|
if ($nodes->length > 0) { |
74
|
|
|
return new Node($nodes[0]); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
return new Node(); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|