<?php

declare(strict_types=1);

namespace CliqThemes\UI\Data\Concerns;

/**
 * Helper methods for transforming record columns before returning them to the UI layer.
 */
trait SupportsColumnTransformers
{
    /**
     * @var array<string,callable>
     */
    private array $columnTransformers = [];

    /**
     * Registers a callback that mutates a record prior to being returned to the consumer.
     */
    public function setColumnTransformer(string $column, callable $transformer): void
    {
        $this->columnTransformers[$column] = $transformer;
    }

    /**
     * Removes a previously registered column transformer.
     */
    public function removeColumnTransformer(string $column): void
    {
        unset($this->columnTransformers[$column]);
    }

    /**
     * Removes all column transformers.
     */
    public function clearColumnTransformers(): void
    {
        $this->columnTransformers = [];
    }

    /**
     * @param array<string,mixed> $record
     *
     * @return array<string,mixed>
     */
    protected function applyColumnTransformers(array $record): array
    {
        foreach ($this->columnTransformers as $column => $transformer) {
            $record[$column] = $transformer($record);
        }

        return $record;
    }

    /**
     * Returns the currently registered column transformers.
     *
     * @return array<string,callable>
     */
    protected function columnTransformers(): array
    {
        return $this->columnTransformers;
    }
}
