Passed
Push — master ( cd6f65...3614ed )
by Vladimir
02:32
created

DbService::create()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 8.9197
c 0
b 0
f 0
cc 4
eloc 13
nc 3
nop 1
1
<?php
2
/**
3
 * @link https://github.com/yiimaker/yii2-newsletter
4
 * @copyright Copyright (c) 2017 Yii Maker
5
 * @license BSD 3-Clause License
6
 */
7
8
namespace ymaker\newsletter\common\services;
9
10
use Yii;
11
use yii\base\Component;
12
use yii\base\InvalidConfigException;
13
use yii\data\ActiveDataProvider;
14
use yii\db\Connection;
15
use yii\di\Instance;
16
use ymaker\newsletter\common\events\SubscribeEvent;
17
use ymaker\newsletter\common\models\entities\NewsletterClient;
18
19
/**
20
 * Database service.
21
 *
22
 * @author Vladimir Kuprienko <[email protected]>
23
 * @since 1.0
24
 */
25
class DbService extends Component implements ServiceInterface
26
{
27
    const MODE_GENERIC = 1;
28
    const MODE_EMAIL = 2;
29
30
    /**
31
     * @var string|Connection
32
     */
33
    public $db = 'db';
34
    /**
35
     * @var int
36
     */
37
    private $_mode = self::MODE_EMAIL;
38
    /**
39
     * @var array
40
     */
41
    private $_errors = [];
42
43
44
    /**
45
     * Setter for mode.
46
     *
47
     * @param int $mode
48
     */
49
    public function setMode($mode)
50
    {
51
        $this->_mode = $mode;
52
    }
53
54
    /**
55
     * @return array
56
     */
57
    public function getErrors()
58
    {
59
        return $this->_errors;
60
    }
61
62
    /**
63
     * @inheritdoc
64
     */
65
    public function init()
66
    {
67
        if ($this->_mode !== self::MODE_GENERIC && $this->_mode !== self::MODE_EMAIL) {
68
            throw new InvalidConfigException('Invalid mode config!');
69
        }
70
        $this->db = Instance::ensure($this->db, Connection::class);
71
    }
72
73
    /**
74
     * @inheritdoc
75
     */
76
    public function getModel()
77
    {
78
        return new NewsletterClient();
79
    }
80
81
    /**
82
     * @inheritdoc
83
     */
84
    public function getDataProvider()
85
    {
86
        $query = NewsletterClient::find()->orderBy(['created_at' => SORT_ASC]);
87
88
        return new ActiveDataProvider([
89
            'query' => $query,
90
            'db' => $this->db,
91
        ]);
92
    }
93
94
    /**
95
     * @inheritdoc
96
     */
97
    public function create(array $data)
98
    {
99
        $model = $this->getModel();
100
101
        if ($this->initModel($model, $data)) {
102
            try {
103
                if ($model->insert(false)) {
104
                    $this->trigger(
105
                        SubscribeEvent::EVENT_AFTER_SUBSCRIBE,
106
                        Yii::createObject([
107
                            'class' => SubscribeEvent::class,
108
                            'contacts' => $model->contacts,
109
                        ])
110
                    );
111
                    return true;
112
                }
113
            } catch (\Exception $ex) {
114
                throw $ex;
115
            }
116
        }
117
118
        return false;
119
    }
120
121
    /**
122
     * Process post data.
123
     *
124
     * @param NewsletterClient $model
125
     * @param array $data
126
     * @return bool
127
     */
128
    protected function initModel(&$model, array $data)
129
    {
130
        if ($model->load($data)) {
131
            switch ($this->_mode) {
132
                case self::MODE_GENERIC:
133
                    $model->setScenario(NewsletterClient::SCENARIO_DEFAULT);
134
                    break;
135
                case self::MODE_EMAIL:
136
                    $model->setScenario(NewsletterClient::SCENARIO_CONTACTS_EMAIL);
137
                    break;
138
            }
139
140
            if ($model->validate()) {
141
                return true;
142
            }
143
144
            $this->_errors = $model->getErrors();
145
        }
146
        return false;
147
    }
148
}
149