有人知道如何修改Phalcon 4上文件验证器中的messageEmpty吗。我尝试使用与Phalcon 3中相同的方法,但不起作用。
这是我的验证器:
$field->addValidator(new PhalconValidationValidatorFile([
"allowedTypes" => [
"text/plain"
],
"messageEmpty" => 'Message empty',
"messageType" => _('Please upload a txt file')
]));
$field->setLabel(_('Upload List'));
这是我运行$This->form->isValid($_FILES(后得到的消息
object(PhalconMessagesMessages)#192 (2) {
["position":protected]=>
int(0)
["messages":protected]=>
array(1) {
[0]=>
object(PhalconMessagesMessage)#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) "PhalconValidationValidatorFileMimeType"
["metaData":protected]=>
array(0) {
}
}
}
}
最后,我创建了一个自定义验证器:
/**
* Class FileValidator
* @package ApiFormsCoreValidatorsFile
* @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(PhalconValidation $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')
]));