MatricesExpander.kt

  1. /**
  2.  * This file is part of the pl.wrzasq.cform.
  3.  *
  4.  * @license http://mit-license.org/ The MIT license
  5.  * @copyright 2023 - 2024 © by Rafał Wrzeszcz - Wrzasq.pl.
  6.  */

  7. package pl.wrzasq.cform.macro.processors

  8. import pl.wrzasq.cform.macro.matrix.MatricesManager
  9. import pl.wrzasq.cform.macro.template.CallsExpander
  10. import pl.wrzasq.cform.macro.template.SECTION_RESOURCES
  11. import pl.wrzasq.cform.macro.template.asMap
  12. import pl.wrzasq.cform.macro.template.mapSelected
  13. import pl.wrzasq.cform.macro.template.popProperty

  14. private const val KEY_MATRIX = "Matrix"

  15. /**
  16.  * Handles expanding matrices into collections of resources.
  17.  */
  18. class MatricesExpander {
  19.     /**
  20.      * Handles input template.
  21.      *
  22.      * @param input Current template state.
  23.      * @param params Template parameter values.
  24.      * @return Processed template.
  25.      */
  26.     fun expand(input: Map<String, Any>, params: Map<String, Any>): Map<String, Any> {
  27.         val manager = MatricesManager()
  28.         val rest = input.mapSelected(SECTION_RESOURCES) {
  29.             asMap(it).filter { (id, element) ->
  30.                 val resource = asMap(element)

  31.                 // for now, we exclude matrix-resources - will be inserted once resolved
  32.                 if (resource.containsKey(KEY_MATRIX)) {
  33.                     resource.popProperty(KEY_MATRIX, { matrix ->
  34.                         manager.buildMatrix(id, resource.filterKeys { key -> key != KEY_MATRIX }, asMap(matrix), params)
  35.                     })
  36.                     false
  37.                 } else {
  38.                     true
  39.                 }
  40.             }
  41.         }

  42.         // avoid unnecessary work and resources
  43.         return if (manager.isEmpty()) {
  44.             input
  45.         } else {
  46.             val callsExpander = CallsExpander(manager)

  47.             callsExpander.processTemplate(
  48.                 rest.mapSelected(SECTION_RESOURCES) {
  49.                     asMap(it) + manager.generateResources()
  50.                 },
  51.                 params,
  52.             )
  53.         }
  54.     }
  55. }