<?php
/**
 * @package    Grav\Framework\Object
 *
 * @copyright  Copyright (C) 2015 - 2018 Trilby Media, LLC. All rights reserved.
 * @license    MIT License; see LICENSE file for details.
 */

namespace Grav\Framework\Object\Property;

/**
 * Array Property Trait
 * @package Grav\Framework\Object\Property
 */
trait ArrayPropertyTrait
{
    /**
     * Properties of the object.
     * @var array
     */
    private $_elements;

    /**
     * @param array $elements
     * @param string $key
     * @throws \InvalidArgumentException
     */
    public function __construct(array $elements = [], $key = null)
    {
        $this->setElements($elements);
        $this->setKey($key);
    }

    /**
     * @param string $property      Object property name.
     * @return bool                 True if property has been defined (can be null).
     */
    protected function doHasProperty($property)
    {
        return array_key_exists($property, $this->_elements);
    }

    /**
     * @param string $property      Object property to be fetched.
     * @param mixed $default        Default value if property has not been set.
     * @param bool $doCreate        Set true to create variable.
     * @return mixed                Property value.
     */
    protected function &doGetProperty($property, $default = null, $doCreate = false)
    {
        if (!$this->doHasProperty($property)) {
            if ($doCreate) {
                $this->_elements[$property] = null;
            } else {
                return $default;
            }
        }

        return $this->_elements[$property];
    }

    /**
     * @param string $property      Object property to be updated.
     * @param string $value         New value.
     */
    protected function doSetProperty($property, $value)
    {
        $this->_elements[$property] = $value;
    }

    /**
     * @param string  $property     Object property to be unset.
     */
    protected function doUnsetProperty($property)
    {
        unset($this->_elements[$property]);
    }

    /**
     * @return array
     */
    protected function getElements()
    {
        return $this->_elements;
    }

    /**
     * @param array $elements
     */
    protected function setElements(array $elements)
    {
        $this->_elements = $elements;
    }

    abstract protected function setKey($key);
}
