<?php

/**
 * The definition for the contact_single_value class.
 *
 * @package CGContacts
 * @category Productivity
 * @author  calguy1000 <calguy1000@cmsmadesimple.org>
 * @copyright Copyright 2014 by Robert Campbell
 */

namespace CGContacts;

/**
 * This is an abstract class that defines an object that supports only a single value, and can only have one of this type.
 */
abstract class contact_single_value extends contact_sub
{
    /**
     * @ignore
     */
    private $_data = array();

    /**
     * Constructor
     *
     * @param contact $parent A reference to the contact object that will own this object.
     */
    public function __construct(contact &$parent) {
        parent::__construct($parent);
        $this->_data['preferred'] = TRUE;
    }

    /**
     * Get the value stored in the object.
     *
     * @return string
     */
    public function get_value()
    {
        return \cge_utils::get_param($this->_data,'value');
    }


    /**
     * Test if this object is a preferred object of its type for this contact.
     * For the contact_single_value objects, this is always true.
     *
     * @return bool
     */
    public function is_preferred()
    {
        return TRUE;
    }

    /**
     * Set the preferred flag for this object.
     * for contact_single_value objects, the preferred status cannot be unset.
     *
     * @param mixed $flag
     */
    public function set_preferred($flag = TRUE)
    {
        $flag = true;
        $this->_data['preferred'] = $flag;
    }

    /**
     * Whether there can be multiple objects of this type associated with a contact.
     *
     * @return bool
     */
    final public function allows_multiple()
    {
        return FALSE;
    }

    /**
     * Set the value associated with this object.
     *
     * @param string $val
     */
    public function set_value($val)
    {
        $val = trim((string) $val);
        $this->_data['value'] = $val;
    }

    /**
     * Validate this object.
     * This method will throw exceptions on an error.
     *
     * @abstract.
     */
    public function validate()
    {
        parent::validate();
        if( !$this->get_value() ) throw new \CmsInvalidDataException('A value is required for each saved contact object');
    }

    /**
     * Get the raw value of this object, suitable for storing in the database.
     *
     * @return string
     */
    public function get_raw_value()
    {
        return $this->get_value();
    }

    /**
     * Convert the object into an array.
     *
     * @ingernal
     * @return array
     */
    public function to_data()
    {
        $out = parent::to_data();
        $out['value'] = $this->get_value();
        return $out;
    }

    /**
     * Fill this object from an array.
     *
     * @param array $data
     */
    public function set_data($data)
    {
        parent::set_data($data);
        $this->_data['value'] = $data['value'];
    }

} // end of class

?>
