Phalcon 4 messageEmpty File Validation - PullRequest
0 голосов
/ 24 марта 2020

Кто-нибудь знает, как изменить messageEmpty в валидаторе файлов на Phalcon 4. Я пытался использовать тот же метод, что и в Phalcon 3, но он не работает.

Это мой валидатор:

$field->addValidator(new \Phalcon\Validation\Validator\File([
    "allowedTypes" => [
        "text/plain"
    ],
    "messageEmpty" => 'Message empty',
    "messageType" => _('Please upload a txt file')
]));

$field->setLabel(_('Upload List'));

Это сообщение я получаю после запуска $ this-> form-> isValid ($ _ FILES)

object(Phalcon\Messages\Messages)#192 (2) {
  ["position":protected]=>
  int(0)
  ["messages":protected]=>
  array(1) {
    [0]=>
    object(Phalcon\Messages\Message)#191 (5) {
      ["code":protected]=>
      int(0)
      ["field":protected]=>
      string(8) "robinson"
      ["message":protected]=>
      string(32) "Field robinson must not be empty"
      ["type":protected]=>
      string(42) "Phalcon\Validation\Validator\File\MimeType"
      ["metaData":protected]=>
      array(0) {
      }
    }
  }
}

1 Ответ

0 голосов
/ 25 марта 2020

Наконец, я создал собственный валидатор:

/**
 * Class FileValidator 
 * @package Api\Forms\Core\Validators\File
 * @author Iulian Gafiu <julian@clickmedia.es>
 */
class FileValidator extends AbstractValidator {

    /**
     * @var array
     */
    protected $params;

    /**
     * IsEmpty constructor.
     * @param array $options
     */
    public function __construct(array $options = []){
        $this->params = $options;
        parent::__construct($options);
    }

    /**
     * @inheritDoc
     */
    public function validate(\Phalcon\Validation $validation, $field): bool{

        if($_FILES[$field]['size'] <= 0){

            if(!isset($this->params['messageEmpty']) || empty($this->params['messageEmpty'])){
                $this->params['messageEmpty'] = sprintf(_('%s cannot be empty'), $field);
            }

            $validation->appendMessage(
                new Message($this->params['messageEmpty'], $field, 'FileEmpty')
            );

            return false;

        }else{


            if(isset($this->params['maxSize']) && !empty($this->params['maxSize'])){
                if($this->human2byte(strtolower($this->params['maxSize'])) < $_FILES[$field]['size']){
                    $validation->appendMessage(
                        new Message($this->params['messageMaxSize'], $field, 'MaxSize')
                    );
                    return false;
                }
            }

            if(isset($this->params['allowedTypes']) && !empty($this->params['allowedTypes'])){
                if(!in_array($_FILES[$field]['type'], $this->params['allowedTypes'])){
                    $validation->appendMessage(
                        new Message($this->params['messageType'], $field, 'allowedTypes')
                    );
                    return false;
                }
            }


        }

        return true;
    }

    /**
     * @param $value
     * @return string|string[]|null
     * @author Eugene Kuzmenko
     * @see https://stackoverflow.com/questions/11807115/php-convert-kb-mb-gb-tb-etc-to-bytes
     */
    public function human2byte($value) {
        return preg_replace_callback('/^\s*(\d+)\s*(?:([kmgt]?)b?)?\s*$/i', function ($m) {
            switch (strtolower($m[2])) {
                case 't': $m[1] *= 1024;
                case 'g': $m[1] *= 1024;
                case 'm': $m[1] *= 1024;
                case 'k': $m[1] *= 1024;
            }
            return $m[1];
        }, $value);
    }

}

Затем я использую его в своей форме:

$field->addValidator(new FileValidator([
    'maxSize' => '112M',
    'allowedTypes' => [
        "text/plain"
    ],
    'messageEmpty' => _('Please upload a file'),
    'messageMaxSize' => _('File size exceeds the max permitted'),
     'messageType' => _('Please upload a formated txt file')
]));
...