1 <?php
2
3 namespace Docoflow\Traits;
4
5 use Exception;
6 use CActiveRecord;
7
8 /**
9 * With this trait, you can create your own entities in so many ways.
10 *
11 * @author Krisan Alfa Timur <krisanalfa@docotel.co.id>
12 */
13 trait Entity
14 {
15 /**
16 * Make an entity statically.
17 *
18 * @param array $stack Array of your entities
19 *
20 * @return mixed
21 */
22 public static function make(array $stack)
23 {
24 $instance = new static();
25
26 return $instance->assign($stack);
27 }
28
29 /**
30 * Bulk assign a data to the entities stack.
31 *
32 * @param array $stack Array of your entities.
33 *
34 * @return mixed
35 */
36 public function assign(array $stack)
37 {
38 foreach ($stack as $value) {
39 $this->push($value);
40 }
41
42 return $this;
43 }
44
45 /**
46 * Bulk save all model in current entity.
47 *
48 * @return void
49 */
50 public function save()
51 {
52 foreach ($this as $model) {
53 if ($model instanceof CActiveRecord) {
54
55 if (container()->bound(get_class(container('docoflow.connection')))) {
56 $model->save();
57 } else {
58 $transaction = transaction(container('docoflow.connection'));
59
60 try {
61 $model->save();
62
63 $transaction->commit();
64 } catch (Exception $e) {
65 $transaction->rollback();
66
67 throw $e;
68 }
69 }
70 }
71 }
72 }
73 }
74