<?php

/*
*

 ______   _______  __   __  _______  _______  ___   _______ 
|      | |       ||  |_|  ||       ||       ||   | |       |
|  _    ||    ___||       ||   _   ||_     _||   | |       |
| | |   ||   |___ |       ||  | |  |  |   |  |   | |       |
| |_|   ||    ___||       ||  |_|  |  |   |  |   | |      _|
|       ||   |___ | ||_|| ||       |  |   |  |   | |     |_ 
|______| |_______||_|   |_||_______|  |___|  |___| |_______|
 _______  __   __  _______                                  
|       ||  |_|  ||       |                                 
|       ||       ||  _____|                                 
|       ||       || |_____                                  
|      _||       ||_____  |                                 
|     |_ | ||_|| | _____| |                                 
|_______||_|   |_||_______|                                                   
                                              
                                           
*
*
*/

/**
 * Demotic CMS is a fork of ImpressPages.
 * AUTHOR: Demotic
 * @package Demotic
 */

namespace Demotic\Form\Validator;

use Demotic\Form\Validator;


class MinLength extends Validator
{
    protected $minLength;

    public function __construct($data = array(), $errorMessage = null)
    {
        $this->minLength = (int)$data;
        $this->errorMessage = $errorMessage;
        if (!is_numeric($data)) {
            throw new \Demotic\Exception('minLength validator expect integer number as a first parameter');
        }
        parent::__construct($data, $errorMessage);
    }

    /**
     * Get error
     *
     * @param array $values all submitted data
     * @param int $valueKey key of value to be validated
     * @param $environment
     * @return string|bool
     */
    public function getError($values, $valueKey, $environment)
    {
        if (!empty($values[$valueKey]) && mb_strlen($values[$valueKey]) < $this->minLength ) {
            if ($environment == \Demotic\Form::ENVIRONMENT_ADMIN) {
                $errorText = sprintf(__('Min %d characters', 'Demotic-admin'), $this->minLength);
            } else {
                $errorText = sprintf(__('Min %d character', 'Demotic'), $this->minLength);;
            }

            return $errorText;
        } else {
            return false;
        }
    }

    /**
     * Validator attributes
     *
     * @return string
     */
    public function validatorAttributes()
    {
        return 'pattern="(.+){' . $this->minLength . ',}"';
    }
}
