commit
68a8ff2887
@ -8,23 +8,38 @@ public extension PureXML.Validation {
|
||||
/// warning finding. Both are ``ValidationError`` values carrying the message.
|
||||
///
|
||||
/// Within a pattern a node is processed by the first rule whose context
|
||||
/// selects it. Dynamic message content (`<value-of>`, `<name>`) is rendered as
|
||||
/// its static text; the message substitution itself is not evaluated.
|
||||
/// selects it. Dynamic message content is evaluated: `<value-of select=>`
|
||||
/// renders the string value of its XPath at the context node, and `<name>`
|
||||
/// renders the node's name, so a finding can report actual values. A `<phase>`
|
||||
/// (or the schema's `defaultPhase`) scopes which patterns run.
|
||||
struct Schematron {
|
||||
private let patterns: [SchematronPattern]
|
||||
private let schema: SchematronSchema
|
||||
|
||||
/// Compiles a Schematron schema document. Throws if a context or test is
|
||||
/// not a valid XPath expression.
|
||||
public init(schema xml: String) throws {
|
||||
patterns = try SchematronParser.parse(xml)
|
||||
schema = try SchematronParser.parse(xml)
|
||||
}
|
||||
|
||||
/// Validates an XML document against the schema, returning one finding per
|
||||
/// failed assertion and per matched report, in document order. Assertions
|
||||
/// are errors and reports are warnings.
|
||||
public func validate(_ xml: String) throws -> [ValidationError] {
|
||||
/// are errors and reports are warnings. With `phase` (or the schema's
|
||||
/// `defaultPhase`), only the patterns that phase activates run; nil or
|
||||
/// `#ALL` runs every pattern.
|
||||
public func validate(_ xml: String, phase: String? = nil) throws -> [ValidationError] {
|
||||
let node = try PureXML.parse(xml)
|
||||
return Validator<Void>.blank.validating(Self.rule(patterns)).errors(for: node, in: ())
|
||||
return Validator<Void>.blank.validating(Self.rule(activePatterns(phase: phase))).errors(for: node, in: ())
|
||||
}
|
||||
|
||||
/// The patterns active in the requested phase, falling back to the schema's
|
||||
/// declared default phase; all patterns when no phase scopes them.
|
||||
private func activePatterns(phase requested: String?) -> [SchematronPattern] {
|
||||
let selected = requested ?? schema.defaultPhase
|
||||
guard let selected, selected != "#ALL", let active = schema.phases[selected] else {
|
||||
return schema.patterns
|
||||
}
|
||||
let ids = Set(active)
|
||||
return schema.patterns.filter { $0.id.map(ids.contains) ?? false }
|
||||
}
|
||||
|
||||
/// The schema as a single ``Validation`` over the document root, so it
|
||||
@ -58,14 +73,29 @@ public extension PureXML.Validation {
|
||||
for assertion in assertions {
|
||||
let holds = (try? assertion.test.value(at: node).boolean) ?? false
|
||||
if assertion.isReport {
|
||||
if holds { errors.append(ValidationError(reason: assertion.message, at: path, severity: .warning)) }
|
||||
if holds { errors.append(ValidationError(reason: render(assertion.message, at: node), at: path, severity: .warning)) }
|
||||
} else if !holds {
|
||||
errors.append(ValidationError(reason: assertion.message, at: path, severity: .error))
|
||||
errors.append(ValidationError(reason: render(assertion.message, at: node), at: path, severity: .error))
|
||||
}
|
||||
}
|
||||
return errors
|
||||
}
|
||||
|
||||
/// Renders a message template against the context node: literal text as is,
|
||||
/// `<value-of>` as the string value of its XPath, `<name>` as the node's
|
||||
/// name. Whitespace runs are collapsed so the rendered message reads
|
||||
/// cleanly regardless of source indentation.
|
||||
private static func render(_ parts: [SchematronMessagePart], at node: PureXML.Model.TreeNode) -> String {
|
||||
let joined = parts.map { part -> String in
|
||||
switch part {
|
||||
case let .text(text): text
|
||||
case let .valueOf(query): (try? query.value(at: node).string) ?? ""
|
||||
case .name: node.name?.description ?? ""
|
||||
}
|
||||
}.joined()
|
||||
return joined.split(whereSeparator: \.isWhitespace).joined(separator: " ")
|
||||
}
|
||||
|
||||
/// The coding path of a context node, built from the element chain to the
|
||||
/// root (a sibling index only when a name repeats), so each finding is
|
||||
/// located at the node its rule fired on rather than the document root.
|
||||
|
||||
@ -1,10 +1,20 @@
|
||||
extension PureXML.Validation {
|
||||
/// One `<assert>` or `<report>`: a compiled XPath test and its message. An
|
||||
/// assert flags when its test is false; a report flags when its test is true.
|
||||
/// One piece of an assertion message: literal text, a `<value-of select=>`
|
||||
/// whose XPath is evaluated against the context node, or a `<name>` rendering
|
||||
/// the context node's name. Lets a finding report actual values.
|
||||
enum SchematronMessagePart {
|
||||
case text(String)
|
||||
case valueOf(PureXML.XPath.Query)
|
||||
case name
|
||||
}
|
||||
|
||||
/// One `<assert>` or `<report>`: a compiled XPath test and its message
|
||||
/// template. An assert flags when its test is false; a report flags when its
|
||||
/// test is true.
|
||||
struct SchematronAssertion {
|
||||
let isReport: Bool
|
||||
let test: PureXML.XPath.Query
|
||||
let message: String
|
||||
let message: [SchematronMessagePart]
|
||||
}
|
||||
|
||||
/// One `<rule>`: a compiled context that selects the nodes the rule fires on,
|
||||
@ -14,9 +24,19 @@ extension PureXML.Validation {
|
||||
let assertions: [SchematronAssertion]
|
||||
}
|
||||
|
||||
/// One `<pattern>`: a list of rules. A node is processed by the first rule in
|
||||
/// the pattern whose context selects it (the ISO Schematron firing rule).
|
||||
/// One `<pattern>`: an optional id (referenced by `<active>` in a phase) and a
|
||||
/// list of rules. A node is processed by the first rule in the pattern whose
|
||||
/// context selects it (the ISO Schematron firing rule).
|
||||
struct SchematronPattern {
|
||||
let id: String?
|
||||
let rules: [SchematronRule]
|
||||
}
|
||||
|
||||
/// A compiled Schematron schema: its patterns and its phases (each phase id
|
||||
/// mapped to the pattern ids it activates), plus the declared default phase.
|
||||
struct SchematronSchema {
|
||||
let patterns: [SchematronPattern]
|
||||
let phases: [String: [String]]
|
||||
let defaultPhase: String?
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,15 +1,31 @@
|
||||
extension PureXML.Validation {
|
||||
/// Parses a Schematron schema document into patterns. Namespace-agnostic: it
|
||||
/// matches the `schema`, `pattern`, `rule`, `assert`, and `report` elements by
|
||||
/// local name, so both the ISO and the legacy Schematron namespaces work.
|
||||
/// Parses a Schematron schema document into patterns and phases. Namespace
|
||||
/// agnostic: it matches the `schema`, `phase`, `active`, `pattern`, `rule`,
|
||||
/// `assert`, and `report` elements by local name, so both the ISO and the
|
||||
/// legacy Schematron namespaces work.
|
||||
enum SchematronParser {
|
||||
static func parse(_ xml: String) throws -> [SchematronPattern] {
|
||||
static func parse(_ xml: String) throws -> SchematronSchema {
|
||||
let root = try PureXML.parseTree(xml)
|
||||
return try descendants(root, localName: "pattern").map(pattern)
|
||||
let schema = descendants(root, localName: "schema").first ?? root
|
||||
let patterns = try descendants(root, localName: "pattern").map(pattern)
|
||||
return SchematronSchema(
|
||||
patterns: patterns,
|
||||
phases: phases(root),
|
||||
defaultPhase: attribute(schema, "defaultPhase"),
|
||||
)
|
||||
}
|
||||
|
||||
private static func phases(_ root: PureXML.Model.TreeNode) -> [String: [String]] {
|
||||
var result: [String: [String]] = [:]
|
||||
for phase in descendants(root, localName: "phase") {
|
||||
guard let id = attribute(phase, "id") else { continue }
|
||||
result[id] = children(phase, localName: "active").compactMap { attribute($0, "pattern") }
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
private static func pattern(_ node: PureXML.Model.TreeNode) throws -> SchematronPattern {
|
||||
try SchematronPattern(rules: children(node, localName: "rule").compactMap(rule))
|
||||
try SchematronPattern(id: attribute(node, "id"), rules: children(node, localName: "rule").compactMap(rule))
|
||||
}
|
||||
|
||||
private static func rule(_ node: PureXML.Model.TreeNode) throws -> SchematronRule? {
|
||||
@ -22,14 +38,31 @@ extension PureXML.Validation {
|
||||
|
||||
private static func assertion(_ node: PureXML.Model.TreeNode) throws -> SchematronAssertion? {
|
||||
guard let test = attribute(node, "test") else { return nil }
|
||||
let isReport = node.name?.localName == "report"
|
||||
return try SchematronAssertion(
|
||||
isReport: isReport,
|
||||
isReport: node.name?.localName == "report",
|
||||
test: PureXML.XPath.Query(test),
|
||||
message: node.stringValue.trimmingXMLWhitespace(),
|
||||
message: messageParts(node),
|
||||
)
|
||||
}
|
||||
|
||||
/// Builds an assertion message template from a node's children: text nodes
|
||||
/// become literal parts, `<value-of select=>` an XPath part, and `<name>` a
|
||||
/// context-name part. The parts render against the context node at
|
||||
/// validation time.
|
||||
private static func messageParts(_ node: PureXML.Model.TreeNode) throws -> [SchematronMessagePart] {
|
||||
var parts: [SchematronMessagePart] = []
|
||||
for child in node.children {
|
||||
if child.kind == .text || child.kind == .cdata {
|
||||
parts.append(.text(child.value))
|
||||
} else if child.kind == .element, child.name?.localName == "value-of", let select = attribute(child, "select") {
|
||||
try parts.append(.valueOf(PureXML.XPath.Query(select)))
|
||||
} else if child.kind == .element, child.name?.localName == "name" {
|
||||
parts.append(.name)
|
||||
}
|
||||
}
|
||||
return parts
|
||||
}
|
||||
|
||||
private static func isAssertion(_ node: PureXML.Model.TreeNode) -> Bool {
|
||||
node.name?.localName == "assert" || node.name?.localName == "report"
|
||||
}
|
||||
|
||||
81
Tests/SchematronDynamicTests.swift
Normal file
81
Tests/SchematronDynamicTests.swift
Normal file
@ -0,0 +1,81 @@
|
||||
@testable import PureXML
|
||||
import Testing
|
||||
|
||||
@Suite("Schematron dynamic messages and phases")
|
||||
struct SchematronDynamicTests {
|
||||
private func validate(_ schema: String, _ xml: String, phase: String? = nil) throws -> [PureXML.Validation.ValidationError] {
|
||||
try PureXML.Validation.Schematron(schema: schema).validate(xml, phase: phase)
|
||||
}
|
||||
|
||||
@Test("value-of renders the actual value in an assertion message")
|
||||
func test_valueOf() throws {
|
||||
let schema = """
|
||||
<schema xmlns="http://purl.oclc.org/dsdl/schematron">
|
||||
<pattern>
|
||||
<rule context="age">
|
||||
<assert test="number(.) < 100">Age <value-of select="."/> must be under 100</assert>
|
||||
</rule>
|
||||
</pattern>
|
||||
</schema>
|
||||
"""
|
||||
let errors = try validate(schema, "<age>120</age>")
|
||||
#expect(errors.count == 1)
|
||||
#expect(errors.first?.reason == "Age 120 must be under 100")
|
||||
}
|
||||
|
||||
@Test("name renders the context element's name")
|
||||
func test_name() throws {
|
||||
let schema = """
|
||||
<schema xmlns="http://purl.oclc.org/dsdl/schematron">
|
||||
<pattern>
|
||||
<rule context="item">
|
||||
<assert test="@id">Element <name/> needs an id</assert>
|
||||
</rule>
|
||||
</pattern>
|
||||
</schema>
|
||||
"""
|
||||
let errors = try validate(schema, "<item/>")
|
||||
#expect(errors.count == 1)
|
||||
#expect(errors.first?.reason == "Element item needs an id")
|
||||
}
|
||||
|
||||
@Test("A phase activates only its listed patterns")
|
||||
func test_phase() throws {
|
||||
let schema = """
|
||||
<schema xmlns="http://purl.oclc.org/dsdl/schematron">
|
||||
<phase id="basic">
|
||||
<active pattern="p1"/>
|
||||
</phase>
|
||||
<pattern id="p1">
|
||||
<rule context="a"><assert test="false()">a is bad</assert></rule>
|
||||
</pattern>
|
||||
<pattern id="p2">
|
||||
<rule context="b"><assert test="false()">b is bad</assert></rule>
|
||||
</pattern>
|
||||
</schema>
|
||||
"""
|
||||
let xml = "<root><a/><b/></root>"
|
||||
// The basic phase runs only p1, so only the a-rule fires.
|
||||
let basic = try validate(schema, xml, phase: "basic")
|
||||
#expect(basic.count == 1)
|
||||
#expect(basic.first?.reason == "a is bad")
|
||||
// With no phase, every pattern runs.
|
||||
#expect(try validate(schema, xml).count == 2)
|
||||
// #ALL runs every pattern.
|
||||
#expect(try validate(schema, xml, phase: "#ALL").count == 2)
|
||||
}
|
||||
|
||||
@Test("defaultPhase scopes patterns when no phase is requested")
|
||||
func test_defaultPhase() throws {
|
||||
let schema = """
|
||||
<schema xmlns="http://purl.oclc.org/dsdl/schematron" defaultPhase="only-a">
|
||||
<phase id="only-a"><active pattern="p1"/></phase>
|
||||
<pattern id="p1"><rule context="a"><assert test="false()">a is bad</assert></rule></pattern>
|
||||
<pattern id="p2"><rule context="b"><assert test="false()">b is bad</assert></rule></pattern>
|
||||
</schema>
|
||||
"""
|
||||
let errors = try validate(schema, "<root><a/><b/></root>")
|
||||
#expect(errors.count == 1)
|
||||
#expect(errors.first?.reason == "a is bad")
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user