<?php
/**
 * Shared helpers for variable source implementations.
 *
 * @package 100Prints
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

abstract class Hundred_Prints_Abstract_Variable_Source implements Hundred_Prints_Variable_Source_Interface {

	/**
	 * Get editor field schemas for this source.
	 *
	 * @return array
	 */
	public function get_fields() {
		return [];
	}

	/**
	 * Sanitize one mapping rule for this source.
	 *
	 * @param array $rule Raw mapping rule.
	 * @return array
	 */
	public function sanitize_rule( array $rule ) {
		$sanitized = [
			'source' => sanitize_key( $this->get_key() ),
		];

		if ( isset( $rule['key'] ) ) {
			$sanitized['key'] = sanitize_text_field( $rule['key'] );
		}

		foreach ( $this->get_fields() as $field ) {
			$field_key = isset( $field['key'] ) ? $field['key'] : '';
			if ( '' === $field_key ) {
				continue;
			}

			if ( array_key_exists( $field_key, $rule ) ) {
				$sanitized[ $field_key ] = Hundred_Prints_Variable_Source_Registry::sanitize_field_value( $field, $rule[ $field_key ] );
			}
		}

		if ( isset( $rule['sub_key'] ) ) {
			$sanitized['sub_key'] = sanitize_text_field( $rule['sub_key'] );
		}

		if ( isset( $rule['staticValue'] ) ) {
			$sanitized['staticValue'] = sanitize_text_field( $rule['staticValue'] );
		}

		return $sanitized;
	}

	/**
	 * Read the first available value from a rule.
	 *
	 * @param array        $rule    Mapping rule.
	 * @param array|string $keys    Ordered keys to check.
	 * @param mixed        $default Default value.
	 * @return mixed
	 */
	protected function get_rule_value( array $rule, $keys, $default = '' ) {
		foreach ( (array) $keys as $key ) {
			if ( isset( $rule[ $key ] ) && '' !== $rule[ $key ] ) {
				return $rule[ $key ];
			}
		}

		return $default;
	}
}
