Errors.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. /*
  3. * FecShop file.
  4. *
  5. * @link http://www.fecshop.com/
  6. * @copyright Copyright (c) 2016 FecShop Software LLC
  7. * @license http://www.fecshop.com/license/
  8. */
  9. namespace fecshop\services\helper;
  10. use fecshop\services\Service;
  11. use Yii;
  12. /**
  13. * Errors sub-service of helper service.
  14. * @author Terry Zhao <2358269014@qq.com>
  15. * @since 1.0
  16. */
  17. class Errors extends Service
  18. {
  19. protected $_errors = false;
  20. public $status = true;
  21. /**
  22. * 添加一条错误信息
  23. * @param string $errors 错误信息,支持模板格式
  24. * @param array $arr 错误信息模板中变量替换对应的数组
  25. * Yii::$service->helper->errors->add('Hello, {username}!', ['username' => $username])
  26. */
  27. public function add($errors, $arr = [])
  28. {
  29. if ($errors) {
  30. $errors = Yii::$service->page->translate->__($errors, $arr);
  31. $this->_errors[] = $errors;
  32. }
  33. }
  34. /**
  35. * @param $model_errors | Array
  36. * Yii2的model在使用rules验证数据格式的时候,报错保存在errors中
  37. * 本函数将errors的内容添加到errors services中。
  38. */
  39. public function addByModelErrors($model_errors)
  40. {
  41. $error_arr = [];
  42. if (is_array($model_errors)) {
  43. foreach ($model_errors as $errors) {
  44. $arr = [];
  45. foreach ($errors as $s) {
  46. $arr[] = Yii::$service->page->translate->__($s);
  47. }
  48. $error_arr[] = implode(',', $arr);
  49. }
  50. if (!empty($error_arr)) {
  51. $this->_errors[] = implode(',', $error_arr);
  52. }
  53. }
  54. }
  55. public function getModelErrorsStrFormat($model_errors)
  56. {
  57. $error_arr = [];
  58. if (is_array($model_errors)) {
  59. foreach ($model_errors as $errors) {
  60. $arr = [];
  61. foreach ($errors as $s) {
  62. $arr[] = Yii::$service->page->translate->__($s);
  63. }
  64. $error_arr[] = implode(',', $arr);
  65. }
  66. if (!empty($error_arr)) {
  67. return implode(',', $error_arr);
  68. }
  69. }
  70. }
  71. /**
  72. * @param $separator 如果是false,则返回数组,
  73. * 如果是true则返回用| 分隔的字符串
  74. * 如果是传递的分隔符的值,譬如“,”,则返回用这个分隔符分隔的字符串
  75. */
  76. public function get($separator = false)
  77. {
  78. if ($errors = $this->_errors) {
  79. $this->_errors = false;
  80. if (is_array($errors) && !empty($errors)) {
  81. if ($separator) {
  82. if ($separator === true) {
  83. $separator = '|';
  84. }
  85. return implode($separator, $errors);
  86. } else {
  87. return $errors;
  88. }
  89. }
  90. }
  91. return false;
  92. }
  93. }