Context.kt

  1. package com.hexagontk.handlers

  2. /**
  3.  * Context for an event.
  4.  *
  5.  * @param T Event type.
  6.  */
  7. interface Context<T : Any> {
  8.     var event: T
  9.     var predicate: (Context<T>) -> Boolean
  10.     var nextHandlers: Array<Handler<T>>
  11.     var nextHandler: Int
  12.     var exception: Exception?
  13.     var attributes: Map<*, *>
  14.     var handled: Boolean

  15.     fun with(
  16.         event: T = this.event,
  17.         predicate: (Context<T>) -> Boolean = this.predicate,
  18.         nextHandlers: Array<Handler<T>> = this.nextHandlers,
  19.         nextHandler: Int = this.nextHandler,
  20.         exception: Exception? = this.exception,
  21.         attributes: Map<*, *> = this.attributes,
  22.         handled: Boolean = this.handled,
  23.     ): Context<T>

  24.     fun next(): Context<T> {
  25.         for (index in nextHandler until nextHandlers.size) {
  26.             val handler = nextHandlers[index]
  27.             val p = handler.predicate
  28.             if (handler is OnHandler) {
  29.                 if ((!handled) && p(this))
  30.                     return handler.process(with(predicate = p, nextHandler = index + 1))
  31.             }
  32.             else {
  33.                 if (p(this))
  34.                     return handler.process(with(predicate = p, nextHandler = index + 1))
  35.             }
  36.         }

  37.         return this
  38.     }
  39. }