depage-xmldb v2.3.1
XML documents in a relational database
Loading...
Searching...
No Matches
Indexer.php
Go to the documentation of this file.
1<?php
2
3namespace Depage\XmlDb;
4
25{
26 protected XmlDb $xmlDb;
27
31 public function __construct(XmlDb $xmlDb)
32 {
33 $this->xmlDb = $xmlDb;
34 }
35
50 public function query(string $xpath, ?int $docId = null): array
51 {
52 [$elementXpath, $attrName] = $this->splitAttribute($xpath);
53
54 $nodeIds = $this->xmlDb->getNodeIdsByXpath($elementXpath, $docId);
55 $nodeIds = is_array($nodeIds) ? $nodeIds : [];
56
57 if (empty($nodeIds)) {
58 return [];
59 }
60
61 $nodeData = $this->xmlDb->getIndexNodeData($nodeIds);
62
63 $texts = null;
64 if (is_null($attrName)) {
65 $texts = $this->xmlDb->getIndexTextContent($nodeIds);
66 }
67
68 $results = [];
69
70 foreach ($nodeIds as $nodeId) {
71 if (!isset($nodeData[$nodeId])) {
72 continue;
73 }
74 $attributes = $nodeData[$nodeId]['attributes'];
75
76 $lang = $attributes['lang'] ?? null;
77
78 if (is_null($attrName)) {
79 $value = $texts[$nodeId] ?? '';
80 } else {
81 // a missing attribute yields no result at all
82 if (!isset($attributes[$attrName])) {
83 continue;
84 }
85
86 $value = $attributes[$attrName];
87 }
88
89 $results[] = new IndexerResult(
90 $nodeData[$nodeId]['doc_id'],
91 $nodeId,
92 $lang,
93 $value,
94 );
95 }
96
97 return $results;
98 }
99
114 protected function splitAttribute(string $xpath): array
115 {
116 $attrName = null;
117 $elementXpath = $xpath;
118
119 // a trailing "/@name" reference (preceded by '/', at the end of the
120 // path) targets the attribute; the remaining path is the element
121 if (preg_match('/^(.+?)\/@([\w\-.:]+)(?:\‍[[^\‍]]*\‍])?\s*$/', $xpath, $matches)) {
122 $attrName = $matches[2];
123 $elementXpath = $matches[1];
124 }
125
126 return [$elementXpath, $attrName];
127 }
128}
129
130/* vim:set ft=php sw=4 sts=4 fdm=marker et : */
splitAttribute(string $xpath)
detects whether the xpath targets an attribute and separates the attribute reference from the element...
Definition Indexer.php:114
__construct(XmlDb $xmlDb)
Definition Indexer.php:31
query(string $xpath, ?int $docId=null)
resolves an xpath query to a list of IndexerResult objects
Definition Indexer.php:50