Completed
Push — master ( 68b0cd...68bcf1 )
by Vladimir
02:30
created

DbService   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 167
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 27
dl 0
loc 167
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 3 1
B create() 0 23 5
B getTranslationModel() 0 14 5
A getModel() 0 6 3
B processData() 0 18 7
A getDataProvider() 0 4 1
A getErrors() 0 3 1
A update() 0 12 3
A getDefaultTranslationModel() 0 3 1
1
<?php
2
/**
3
 * @link https://github.com/yiimaker/yii2-email-templates
4
 * @copyright Copyright (c) 2017 Yii Maker
5
 * @license BSD 3-Clause License
6
 */
7
8
namespace ymaker\email\templates\services;
9
10
use Yii;
11
use yii\base\Object;
12
use yii\data\ActiveDataProvider;
13
use yii\db\Connection;
14
use yii\di\Instance;
15
use yii\helpers\ArrayHelper;
16
use ymaker\email\templates\models\entities\EmailTemplate;
17
use ymaker\email\templates\models\entities\EmailTemplateTranslation;
18
19
/**
20
 * Database service.
21
 *
22
 * @author Vladimir Kuprienko <[email protected]>
23
 * @since 1.0
24
 */
25
class DbService extends Object implements ServiceInterface
26
{
27
    /**
28
     * Database connection instance.
29
     *
30
     * @var \yii\db\Connection
31
     */
32
    public $db = 'db';
33
34
    /**
35
     * @var EmailTemplate
36
     */
37
    protected $_template;
38
    /**
39
     * @var EmailTemplateTranslation
40
     */
41
    protected $_translation;
42
    /**
43
     * @var array errors from model.
44
     * @since 2.1
45
     */
46
    private $_errors = [];
47
48
49
    /**
50
     * @inheritdoc
51
     */
52
    public function init()
53
    {
54
        $this->db = Instance::ensure($this->db, Connection::class);
55
    }
56
57
    /**
58
     * @inheritdoc
59
     */
60
    public function getModel($id = null)
61
    {
62
        if ($id !== null && ($model = EmailTemplate::findOne($id))) {
63
            return $model;
64
        }
65
        return new EmailTemplate();
66
    }
67
68
    /**
69
     * @inheritdoc
70
     */
71
    public function getTranslationModel($modelId = null, $language = null)
72
    {
73
        if ($modelId !== null && $language !== null) {
74
            $params = [
75
                'templateId' => $modelId,
76
                'language' => $language
77
            ];
78
            $model = EmailTemplateTranslation::findOne($params);
79
80
            return $model ?: new EmailTemplateTranslation($params);
81
        }
82
83
        return new EmailTemplateTranslation([
84
            'language' => $language ?: Yii::$app->language,
85
        ]);
86
    }
87
88
    /**
89
     * @inheritdoc
90
     */
91
    public function getDefaultTranslationModel($modelId)
92
    {
93
        return EmailTemplateTranslation::findOne(['templateId' => $modelId]);
94
    }
95
96
    /**
97
     * @inheritdoc
98
     */
99
    public function getDataProvider()
100
    {
101
        return new ActiveDataProvider([
102
            'query' => EmailTemplate::find()->with('translations'),
103
        ]);
104
    }
105
106
    /**
107
     * @inheritdoc
108
     */
109
    public function getErrors()
110
    {
111
        return $this->_errors;
112
    }
113
114
    /**
115
     * Load and validate data in models.
116
     *
117
     * @param array $data Array with data for models.
118
     * @return array|bool
119
     */
120
    protected function processData(array $data)
121
    {
122
        if ($this->_template->load($data) && $this->_translation->load($data)) {
123
            if ($this->_template->getIsNewRecord()) {
124
                $this->_translation->templateId = 0;
125
            }
126
            if (!$this->_template->validate()) {
127
                $this->_errors = $this->_template->getErrors();
128
            }
129
            if (!$this->_translation->validate()) {
130
                $this->_errors = ArrayHelper::merge(
131
                    $this->_errors,
132
                    $this->_translation->getErrors()
133
                );
134
            }
135
            return empty($this->_errors) ? true : false;
136
        }
137
        return false;
138
    }
139
140
    /**
141
     * Save model in database.
142
     *
143
     * @param array $data
144
     * @return bool
145
     * @throws \Exception
146
     */
147
    public function create($data)
148
    {
149
        $this->_template = $this->getModel();
150
        $this->_translation = $this->getTranslationModel();
151
152
        if ($this->processData($data))  {
153
            $transaction = $this->db->beginTransaction();
154
            try {
155
                $isSaved = $this->_template->insert(false);
156
                $this->_translation->templateId = $this->_template->id;
157
                $isSaved = $this->_translation->insert(false) && $isSaved;
158
                if ($isSaved) {
159
                    $transaction->commit();
160
                    return true;
161
                }
162
                $transaction->rollBack();
163
            } catch (\Exception $ex) {
164
                $transaction->rollBack();
165
                throw $ex;
166
            }
167
        }
168
169
        return false;
170
    }
171
172
    /**
173
     * Save updates models data in database.
174
     *
175
     * @param EmailTemplateTranslation $translation
176
     * @param array $data
177
     * @return array|bool
178
     * @throws \Exception
179
     */
180
    public function update($translation, $data)
181
    {
182
        $this->_translation = $translation;
183
184
        if ($this->_translation->load($data)) {
185
            if (!$this->_translation->validate()) {
186
                return $this->_translation->getErrors();
187
            }
188
            return $this->_translation->save(false);
189
        }
190
191
        return false;
192
    }
193
}
194