<?php

namespace Fab\Helper;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Trait for handling dynamic getters and setters
 *
 * @package    Fab
 * @subpackage Fab/Helper/FAB
 */
trait GetterSetter {

    /**
     * Magic method to handle dynamic getters and setters
     *
     * @param string $name          Method name.
     * @param array  $arguments     Method arguments.
     * @throws \WP_Error If method does not exist.
     * @return mixed
     */
    public function __call( $name, $arguments ) {
        /**
         * Transform Property
         * - Extract property name from method name.
         * - Convert camelCase to underscore if property not exists. ex. getThirdPartyData -> third_party_data.
         * - Remove initial _ from property. ex. get_icon_class -> icon_class.
         */
        $property = lcfirst( substr( $name, 3 ) );
        $property = property_exists( $this, $property ) ? $property : strtolower( preg_replace( '/(?<!^)[A-Z]/', '_$0', $property ) );
        $property = property_exists( $this, $property ) ? $property : ltrim( $property, '_' );

        /**
         * Handle is and get.
         *
         * EXAMPLE:
         * - isTobeDisplayed -> tobe_displayed
         * - getModal -> modal
         */
        if ( property_exists( $this, $property ) &&
            ( strpos( $name, 'is' ) === 0 || strpos( $name, 'get' ) === 0 )
        ) {
            return $this->$property;
        }

        // Handle setter.
        if ( strpos( $name, 'set' ) === 0 && property_exists( $this, $property ) ) {
            /* translators: %s: Property name that is being set */
            if ( ! isset( $arguments[0] ) ) {
                return new \WP_Error(
                    'fab_invalid_argument',
                    sprintf( __( 'No value provided for setting %s', 'floating-awesome-button' ), $property )
                );
            }
            $this->$property = $arguments[0];
            return;
        }

        /* translators: %s: Method name that does not exist */
        return new \WP_Error( 'fab_method_not_found', esc_html( sprintf( __( 'Method %s does not exist.', 'floating-awesome-button' ), $name ) ) );
    }
}
