Blame view

common/components/ModelArrayValidator.php 3.48 KB
c2ef0939   Mihail   add array model v...
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
  <?php
  /**
   * Created by PhpStorm.
   * User: Tsurkanov
   * Date: 26.11.2015
   * Time: 9:04
   */
  
  namespace common\components;
  
  use yii\base\Model;
  
  /**
   * Class ModelArrayValidator
   * @package common\components
   * Валидирует переданный массив, сохраняет отдельно ошибки, и возвращает отвалидированные данные
   * также формирует сообщение на форму с количеством обработанных записей и количеством ошибок
   * использовать когда нужно сохранить только отвалидированные данные,
   * а ошибочные откинуть и показать пользователю в сообщении
   */
  class ModelArrayValidator
  {
      protected $arr_errors = [];
      protected $model;
      protected $valid_data = [];
      protected $total_rows = 0;
  
      public function __construct( Model $model )
      {
          $this->model = $model;
      }
  
      /**
       * @return array
       */
      public function getErrors()
      {
          return $this->arr_errors;
      }
  
      /**
       * @return mixed
       */
      public function getValidData()
      {
          return $this->valid_data;
      }
  
      /**
       * @return string - сообщение на форму с результатми обработки
       */
      public function getMassage ()
      {
          $total_count = $this->total_rows;
          $success_count = $this->total_rows - count($this->arr_errors);
          $error_count = count($this->arr_errors);
  
          $msg = "Обработано - {$total_count} строк.</br>
          Успешно загрузились - {$success_count} строк.</br>
          Найдено строк с ошибками - {$error_count}.</br>";
  
          foreach ($this->arr_errors as $row => $error) {
              $msg .= "Ошибка в строке {$row} </br>
              Текст ошибки: {$error} </br>";
          }
  
          return $msg;
      }
  
      /**
       * @param $data
       * @return array
       * метод регистрирует ошибки, регистрирует "чистые данные" и возвращает их
       */
      public function validate( $data )
      {
          foreach ( $data as $row ) {
              $this->total_rows++;
              $validate_row[$this->model->formName()] = $row;
              // clear previous loading
              $this->clearModelAttributes();
               if ( $this->model->load( $validate_row ) && $this->model->validate() ) {
              // everything OK, registred row to valid data
                  $this->valid_data[] = $row;
               } else{
                   // we have errors
                   $this->registredError( $this->total_rows );
               }
          }
  
          return $this->valid_data;
      }
  
      protected function registredError ($index)
      {
          $errors_str = '';
          foreach ($this->model->getErrors() as $error) {
              $errors_str .= implode(array_values($error));
          }
  
          $this->arr_errors[$index] = $errors_str;
      }
  
  
      public function hasError ()
      {
          return (bool) count($this->arr_errors);
      }
  
      protected function clearModelAttributes()
      {
      $attributes = $this->model->safeAttributes();
  
          foreach ( $attributes as $key => $value ) {
              $this->model->$value = '';
          }
  
  }
  
      public function close(){
  
          unset( $this->valid_data );
          unset( $this->arr_errors );
          unset( $this->model );
  
      }
  }