<?php
namespace nur\mapper\base;

use nur\b\params\Tparametrable;
use nur\func;

/**
 * Class FuncMapper: appeler une fonction pour chaque valeur
 *
 * --autogen-properties-and-methods--
 * @method bool isMarkedOnly()
 * @method callable|null setFunc(?callable $value)
 * @method bool setMarkedOnly(bool $value)
 */
class FuncMapper extends Mapper {
  use Tparametrable;

  function __construct(?callable $func=null, ?iterable $source=null) {
    parent::__construct($source);
    if ($func !== null) $this->pp_setFunc($func);
  }

  /** @var array */
  protected $func;

  function pp_setFunc(callable $func): void {
    $this->func = func::_prepare($func);
  }

  /** @var bool */
  protected $ppMarkedOnly;

  const PARAMETRABLE_PARAMS_SCHEMA = [
    "func" => ["callable", null, "fonction à appeler"],
    "marked_only" => ["bool", null, "n'appeler la fonction que pour les éléments marqués"],
  ];

  protected function setup(): void {
    parent::setup();
    if ($this->ppMarkedOnly === null) {
      $this->ppMarkedOnly = mark_utils::is_use_marks($this);
    }
  }

  function mapper($item, $key=null) {
    if (!$this->ppMarkedOnly || $this->isItemMarked($item)) {
      $item = func::_call($this->func, [$item, $key, $this]);
    }
    return $item;
  }

  #############################################################################
  const _AUTOGEN_CONSTS = [
    "" => [self::class, "_autogen_consts"],
  ];
  const _AUTOGEN_LITERALS = /*autogen*/[
    [
      \nur\b\params\parametrable_utils::class,
      '\\nur\\b\\params\\parametrable_utils::class',
    ],
    [
      self::PARAMETRABLE_PARAMS_SCHEMA,
      'self::PARAMETRABLE_PARAMS_SCHEMA',
    ],
  ];
  const _AUTOGEN_METHODS = /*autogen*/[
    [
      \nur\b\params\parametrable_utils::class,
      '_autogen_methods_getters',
      self::PARAMETRABLE_PARAMS_SCHEMA,
      null,
    ],
    [
      \nur\b\params\parametrable_utils::class,
      '_autogen_methods_setters',
      self::PARAMETRABLE_PARAMS_SCHEMA,
      null,
    ],
  ];
  const _AUTO_GETTERS = /*autogen*/[
    'getFunc' => 'func',
    'isMarkedOnly' => 'marked_only',
  ];
  const _AUTO_SETTERS = /*autogen*/[
    'setFunc' => 'func',
    'setMarkedOnly' => 'marked_only',
  ];
  #--autogen-dynamic--
}
