<?php
namespace SaveToWishlist\Traits;

/**
 * Trait Magic_Getter_Setter
 *
 * This trait holds the methods for magic getter and setter.
 */
trait Magic_Getter_Setter {
    /**
     * Get the value of a property.
     * We use this magic method to automatically access data from the data property so
     * we do not need to create individual methods to expose each of the constant properties.
     *
     * @since 1.0.0
     * @access public
     *
     * @param string $prop The name of the data property to access.
     * @return mixed Data property value.
     * @throws \Exception Error message.
     */
    public function __get( $prop ) {
        if ( array_key_exists( $prop, $this->data ) ) {
            return $this->data[ $prop ];
        } else {
            throw new \Exception( esc_html( sprintf( 'Trying to access unknown property %s', $prop ) ) );
        }
    }

    /**
     * Set the value of a property.
     *
     * @since 1.0.0
     * @access public
     *
     * @param string $prop  The name of the data property to access.
     * @param mixed  $value The value to set.
     * @throws \Exception Error message.
     */
    public function __set( $prop, $value ) {
        if ( array_key_exists( $prop, $this->data ) && gettype( $this->data[ $prop ] ) === gettype( $value ) ) {
            $this->data[ $prop ] = $value;
        } else {
            throw new \Exception( esc_html( sprintf( 'Error: Trying to set unknown property %s', $prop ) ) );
        }
    }
}
