Blame view

common/modules/relation/relationBehavior.php 7.63 KB
a8370482   Alexander Karnovsky   init project
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
  <?php
  
  namespace common\modules\relation;
  
  use yii\base\Behavior;
  use yii\base\Exception;
  use yii\db\ActiveRecord;
  use Yii;
  use yii\helpers\ArrayHelper;
  
  class relationBehavior extends Behavior {
  
      /** @var array $fields Form-fields for current relations */
      public $fields = [];
  
      /** @var array $values Values for current relations */
      public $values = [];
  
      /** @var array $relations List of relations of current model */
      public $relations = [];
  
      /**
       * @param ActiveRecord $owner
       * @throws Exception
       */
      public function attach($owner)
      {
          parent::attach($owner);
      }
  
      /*
       * Inicialize behavior (read and prepare params)
       */
      public function init() {
          foreach ($this->relations as $relation_key => &$relation) {
              if (is_string($relation)) {
                  // Get data from module's data
                  $relation_entity = $relation;
                  $relation = $this->_getRelationParams($relation_key);
                  $relation['inner'] = $relation[$relation_entity];
                  $relation['outer'] = $relation[$relation_entity == 'entity1' ? 'entity2' : 'entity1'];
                  $relation['linked_table'] = $relation['via']['model']::tableName();
b15c889e   Karnovsky A   Base-product#2 fu...
43
44
45
                  if (!empty($relation['via']['alias'])) {
                      $relation['linked_alias'] = $relation['via']['alias'];
                  }
a8370482   Alexander Karnovsky   init project
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
              }
              $this->fields[$relation['field']] = $relation_key;
          }
      }
  
      /*
       * Events for auto-drive relations data
       */
      public function events()
      {
          return [
              ActiveRecord::EVENT_AFTER_INSERT    => 'relationsAfterSave',
              ActiveRecord::EVENT_AFTER_UPDATE    => 'relationsAfterSave',
              ActiveRecord::EVENT_BEFORE_DELETE   => 'relationBeforeDelete',
          ];
      }
  
      public function relationsAfterSave($insert) {
          if (is_array($modelPrimaryKey = $this->owner->getPrimaryKey())) {
              throw new ErrorException('This behavior does not support composite primary keys');
          }
b15c889e   Karnovsky A   Base-product#2 fu...
67
  
a8370482   Alexander Karnovsky   init project
68
          foreach ($this->relations as $relation_key => $relation) {
b15c889e   Karnovsky A   Base-product#2 fu...
69
              if (empty($relation['field']) || !is_array($this->{$relation['field']}))
a8370482   Alexander Karnovsky   init project
70
                  continue;
b15c889e   Karnovsky A   Base-product#2 fu...
71
  
a8370482   Alexander Karnovsky   init project
72
73
74
75
76
77
78
79
              $values = $this->{$relation['field']};
  
              /** @var ActiveRecord $model */
              $model = new $relation['inner']['model'];
  
              $connection = $model::getDb();
              $transaction = $connection->beginTransaction();
  
b15c889e   Karnovsky A   Base-product#2 fu...
80
81
82
83
84
              $delete_where = [$relation['inner']['linked_key'] => $this->owner->{$relation['inner']['key']}];
              if (!empty($relation['linked_alias'])) {
                  $delete_where[$relation['linked_alias']] = $relation_key;
              }
  
a8370482   Alexander Karnovsky   init project
85
86
87
88
89
90
              try {
                  // Delete all links from viaTable
                  $connection->createCommand()
                      ->delete
                      (
                          $relation['linked_table'],
b15c889e   Karnovsky A   Base-product#2 fu...
91
                          $delete_where
a8370482   Alexander Karnovsky   init project
92
93
94
95
96
                      )
                      ->execute();
  
                  if (!empty($values)) {
                      foreach($values as $value) {
b15c889e   Karnovsky A   Base-product#2 fu...
97
98
99
100
101
102
103
104
105
                          $insertData = [
                              $relation['inner']['linked_key'] => $this->owner->{$relation['inner']['key']},
                              $relation['outer']['linked_key'] => $value
                          ];
                          if (!empty($relation['linked_alias'])) {
                              $insertData[$relation['linked_alias']] = $relation_key;
                          }
  
  
a8370482   Alexander Karnovsky   init project
106
107
108
109
                          $connection->createCommand()
                              ->insert
                              (
                                  $relation['linked_table'],
b15c889e   Karnovsky A   Base-product#2 fu...
110
                                  $insertData
a8370482   Alexander Karnovsky   init project
111
112
113
114
115
116
117
118
                              )
                              ->execute();
                      }
                  }
                  $transaction->commit();
  
  //                $model->link($relation_key, )
              } catch (Exception $ex) {
b15c889e   Karnovsky A   Base-product#2 fu...
119
  //                var_dump($relation_key, $relation);exit;
a8370482   Alexander Karnovsky   init project
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
                  $transaction->rollback();
                  throw $ex;
              }
          }
      }
  
      public function relationBeforeDelete() {
          if (is_array($modelPrimaryKey = $this->owner->getPrimaryKey())) {
              throw new ErrorException('This behavior does not support composite primary keys');
          }
          foreach ($this->relations as $relation_key => $relation) {
              if (empty($relation['field']))
                  continue;
              $values = $this->{$relation['field']};
  
              /** @var ActiveRecord $model */
              $model = new $relation['inner']['model'];
  
              $connection = $model::getDb();
              $transaction = $connection->beginTransaction();
  
              // @todo Refix to ActiveRecord format
              try {
                  // Delete all links from viaTable
                  $connection->createCommand()
                      ->delete
                      (
                          $relation['linked_table'],
                          [$relation['inner']['linked_key'] => $this->owner->{$relation['inner']['key']}]
                      )
                      ->execute();
                  $transaction->commit();
              } catch (Exception $ex) {
                  $transaction->rollback();
                  throw $ex;
              }
          }
      }
  
      /**
       * Get related data for $relation
       * @params string $relation Relation key
       */
      public function getRelations($relation) {
          $relation = $this->_getRelation($relation);
          return
              $this->owner
                  ->hasMany($relation['outer']['model'], [$relation['outer']['key'] => $relation['outer']['linked_key']])
                  ->viaTable($relation['linked_table'], [$relation['inner']['linked_key'] => $relation['inner']['key']]);
      }
  
      /*
       * Get relation params for $relation
       * @param string $relation Relation key
       */
      protected function _getRelation($relation) {
          $relation = strtolower($relation);
          return isset($this->relations[$relation]) ? $this->relations[$relation] : null;
      }
  
      /**
       * Return relation data from main app config
       * @params string $section Relations key
       */
      protected function _getRelationParams($section) {
          $relation = relationHelper::getRelation($section);
          if (!$relation)
              throw new Exception('Relation "' . $section . '" not set on this application.');
          return $relation;
      }
  
      protected function _getRelationNameByField($field) {
          return isset($this->fields[$field]) ? $this->fields[$field] : null;
      }
  
      protected function _getRelationByField($field) {
          return ( isset($this->fields[$field]) && isset($this->relations[$this->fields[$field]]) ) ? $this->relations[$this->fields[$field]] : null;
      }
  
      /**
       * @inheritdoc
       */
      public function canGetProperty($name, $checkVars = true)
      {
          return true;
      }
  
      /**
       * @inheritdoc
       */
      public function canSetProperty($name, $checkVars = true)
      {
          return array_key_exists($name, $this->fields) ?
              true : parent::canSetProperty($name, $checkVars = true);
      }
  
      /**
       * @inheritdoc
       */
      public function __set($name, $value) {
          if (isset($this->fields[$name])) {
              $this->values[$name] = $value;
          }
      }
  
      /**
       * @inheritdoc
       */
      public function __get($name) {
          if (isset($this->values[$name])) {
              return $this->values[$name];
          } else {
              $relation_key = $this->_getRelationNameByField($name);
              if (!$relation_key)
                  return;
  
              return $this->getRelations($relation_key);
          }
      }
  }