Maslosoft Mangan API
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
<?php
/**
* This software package is licensed under AGPL or Commercial license.
*
* @package maslosoft/mangan
* @licence AGPL or Commercial
* @copyright Copyright (c) Piotr Masełkowski <pmaselkowski@gmail.com>
* @copyright Copyright (c) Maslosoft
* @copyright Copyright (c) Others as mentioned in code
* @link https://maslosoft.com/mangan/
*/
namespace Maslosoft\Mangan\Validators\Traits;
use InvalidArgumentException;
use Maslosoft\Mangan\Meta\ManganMeta;
use Maslosoft\Mangan\Sanitizers\StringSanitizer;
/**
* Basic implementation of messaging for validators
*
* @author Piotr Maselkowski <pmaselkowski at gmail.com>
*/
trait Messages
{
/**
* Custom error message. May contain special placeholders, ie: {attribute}, {value}
* which will be replaced with attribute label or value, depending on validator.
*
* **NOTE**: This message will be used instead of any other validtor messages when set.
*
* @Sanitizer(StringSanitizer)
* @see StringSanitizer
* @var string
*/
public $message = '';
/**
* Error messages
* @var string[]
*/
private $messages = [];
/**
* Add error. Let it be either error message, or validator field with message.
*
* This is meant to be used inside validators.
*
* Will display value of `$msgError` if set or it's Label annotation value:
* ```php
* $this->addError('msgError');
* ```
*
* Will display error message as is:
* ```php
* $this->addError('This field is required');
* ```
*
* **NOTE**: If field `message` is set, it will use this custom message.
*
* @param string $message
* @param string[] $params
*/
public function addError($message, $params = [])
{
// Use custom message
if (!empty($this->message))
{
$message = $this->message;
}
elseif (preg_match('~^[a-zA-Z0-9_]+$~', $message) && isset($this->$message))
{
// Use message from @Label if it's validator field and is empty
if ($this->$message === '')
{
$fieldMeta = ManganMeta::create($this)->field($message);
if (false === $fieldMeta)
{
throw new InvalidArgumentException(sprintf("Unknown validator message field: `%s`", $message));
}
$message = $fieldMeta->label;
}
else
{
$message = $this->$message;
}
}
if (!empty($params))
{
$message = str_replace(array_keys($params), $params, $message);
}
$this->messages[] = $message;
}
/**
* Get error messages for this validator.
*
* This will return array of error messages if any. Order of messages is not guaranteed.
*
* @return string[]
*/
public function getErrors()
{
return $this->messages;
}
}
API documentation generated by ApiGen