<?php

namespace Velis\Model\DataObject;

use Velis\Arrays;

/**
 * Sanitization functionality
 * @author Olek Procki <olo@velis.pl>
 */
trait SanitizeTrait
{
    /**
     * Fields stashed by sanitization
     * @var array
     */
    protected $_stashedFields = [];


    /**
     * Convert empty string into null
     *
     * @param string|string[] $field
     * @return \Velis\Model\DataObject
     */
    protected function _convertNull()
    {
        foreach (func_get_args() as $field) {
            if (!strlen($this[$field])) {
                $this[$field] = null;
            }
        }
        return $this;
    }


    /**
     * Extracts only important fields from selected array
     *
     * @return $this sanitized object
     */
    public function sanitize($stash = true)
    {
        $columns = self::$_db->getColumns($this->_getTableName());
        $fields  = array_keys($columns);
        $complexTypeColumns = array_keys(
            Arrays::byValue($columns, 'data_type', 'USER-DEFINED')
        );

        if (!empty($fields) && is_array($fields)) {
            foreach ($this->getArrayCopy() as $field => $value) {
                if (
                    array_search($field, $fields) === false &&
                    !in_array(substr($field, 0, strpos($field, '.')), $complexTypeColumns)
                ) {
                    if ($stash) {
                        $this->_stashedFields[$field] = $this[$field];
                    }
                    unset($this[$field]);
                }
            }
        }
        return $this;
    }


    /**
     * Recovers stashed fields
     * @return \Velis\Model\DataObject
     */
    public function unstash()
    {
        foreach ($this->_stashedFields as $field => $value) {
            $this[$field] =  $value;
        }
        $this->_stashedFields = [];
        return $this;
    }
}
