<?php namespace Eae\Support;

use Eae\Security\InputCleaner;

/**
* Transforms values based on array on transformation rules
*/

class Formatter
{
    public function instance(){
        return $this;
    }
    
    /**
     * Transforms the Input based on the generic backoffice preValidation value
     * $value [string] -> $value to be transformed
     * $rules [array or string] -> array("trim", "xss_clean") or "trim|xss_clean"
     * returns value transformed
     */ 
    
    public function transformItem($value, $rules){
        $rulesList = $rules;
        
        if(empty($value)){
            return $value;
        }
        
        if(is_string($rulesList)){
            $rulesList = explode("|", $rules);
        }
        
        if(!is_string($value) || !is_array($rulesList)){
            throw new \InvalidArgumentException("The value must be a string and the rules must be a string or array");    
        }

        foreach($rulesList as $rule){
            $method = "transform{$this->_parseRule($rule)}";
            
            if(method_exists($this, $method)){
                $value = $this->$method($value);      
            }else{
                $value = $rule($value);    
            }           
        } 
        
        return $value;
    }
    
    protected function _parseRule($rule){
        return studly_case($rule);
    }
    
    
    protected function transformXssClean($value)
    {
        return InputCleaner::xss_clean($value);
    }

}
