All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.gitlab.mvysny.konsumexml.Names.kt Maven / Gradle / Ivy

There is a newer version: 1.2
Show newest version
package com.gitlab.mvysny.konsumexml

import javax.xml.namespace.QName

/**
 * An element name matcher, matches elements with particular name. Examples:
 * * `of("title")` matches elements with exactly given tag name
 * * `of("name", "surname", "title")` matches elements with any of given tag names
 * * `any()` matches any element with any name. You can also use the convenience constant [anyName].
 */
sealed class Names {
    /**
     * Checks whether this matcher matches element with given [localName] and [namespace].
     */
    abstract fun accepts(localName: String, namespace: String): Boolean

    /**
     * Checks whether this matcher matches element with given [name].
     */
    fun accepts(name: QName) = accepts(name.localPart, name.namespaceURI)

    /**
     * Matches exactly one [name].
     */
    private data class One(val name: String) : Names() {
        override fun accepts(localName: String, namespace: String): Boolean = localName == name
        override fun toString() = "'$name'"
    }

    /**
     * Matches any of given set of [names].
     */
    private data class Multiple(val names: Set) : Names() {
        override fun accepts(localName: String, namespace: String): Boolean = names.contains(localName)
        override fun toString() = "'$names'"
    }

    /**
     * Matches any name.
     */
    private object Any : Names() {
        override fun accepts(localName: String, namespace: String): Boolean = true
        override fun toString() = "any"
    }

    companion object {
        /**
         * Returns a matcher which matches elements with exactly this [name].
         */
        fun of(name: String): Names = One(name)

        /**
         * Returns a matcher which matches elements with any of given [names].
         */
        fun of(vararg names: String): Names {
            check(names.isNotEmpty()) { "name cannot be empty" }
            return when {
                names.size == 1 -> One(names[0])
                else -> Multiple(names.toSet())
            }
        }

        /**
         * Returns a matcher which matches elements with any of given [names].
         */
        fun of(names: Set): Names {
            check(names.isNotEmpty()) { "name cannot be empty" }
            return when {
                names.size == 1 -> One(names.first())
                else -> Multiple(names.toSet())
            }
        }

        /**
         * Returns a matcher which matches element with any name.
         */
        fun any(): Names = Any
    }
}

/**
 * Matches any name.
 */
val anyName: Names = Names.any()




© 2015 - 2024 Weber Informatics LLC | Privacy Policy