<?php

namespace ModulesGarden\OpenXchangeAddon\Core\UI\Traits;

use \ModulesGarden\OpenXchangeAddon\Core\Http\Request;

/** 
 * Adds methods to handle requests data
 */
trait RequestObjectHandler
{
    /** 
     * request object variable
     * @var \ModulesGarden\OpenXchangeAddon\Core\Http\Request
     */
    protected $request = null;
    
    /** 
     * loads request object
     */
    protected function loadRequestObj()
    {
        if ($this->request === null)
        {
            $this->request = Request::build();
        }
        
        return $this;
    }
    
    /** 
     * returns data from request by provided $key or dafault value if key was not found
     * @param string $key
     * @param mixed $defaultValue
     * @return mixed
     */
    public function getRequestValue($key, $defaultValue = false)
    {
        $this->loadRequestObj();

        if ($this->request)
        {
            return $this->request->getValue($key, $defaultValue);
        }
        
        return $defaultValue;
    }

    /**
     * returns array data from request by provided $key or default value if key was not found
     *
     * @param string $key
     * @param array $defaultValue
     * @return array
     */
    public function getArrayRequestValue($key, array $defaultValue = [])
    {
        $this->loadRequestObj();

        if (!$this->request)
        {
            return $defaultValue;
        }

        foreach ([$this->request->attributes->all(), $this->request->query->all(), $this->request->request->all()] as $source)
        {
            if (array_key_exists($key, $source))
            {
                return is_array($source[$key]) ? $source[$key] : $defaultValue;
            }
        }

        return $defaultValue;
    }
}
