BannerService::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
/**
3
 * @link https://github.com/yiimaker/yii2-banner
4
 * @copyright Copyright (c) 2017 Yii Maker
5
 * @license BSD 3-Clause License
6
 */
7
8
namespace ymaker\banner\backend\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\web\NotFoundHttpException;
16
use yii\web\UploadedFile;
17
use ymaker\banner\backend\exceptions\FileUploadException;
18
use ymaker\banner\backend\models\entities\Banner;
19
use ymaker\banner\backend\models\entities\BannerTranslation;
20
use ymaker\banner\common\components\FileManagerInterface;
21
22
/**
23
 * Service for banner.
24
 *
25
 * @author Vladimir Kuprienko <[email protected]>
26
 * @since 1.0
27
 */
28
class BannerService extends Object implements BannerServiceInterface
0 ignored issues
show
Deprecated Code introduced by
The class yii\base\Object has been deprecated with message: since 2.0.13, the class name `Object` is invalid since PHP 7.2, use [[BaseObject]] instead.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
29
{
30
    /**
31
     * @var string|array|Connection
32
     */
33
    private $_db = 'db';
34
    /**
35
     * @var FileManagerInterface
36
     */
37
    private $_fileManager;
38
    /**
39
     * @var Banner
40
     */
41
    private $_model;
42
43
44
    /**
45
     * @inheritdoc
46
     * @param FileManagerInterface $fileManager
47
     */
48
    public function __construct(FileManagerInterface $fileManager, $config = [])
49
    {
50
        $this->_fileManager = $fileManager;
51
        parent::__construct($config);
52
    }
53
54
    /**
55
     * @param string|array|Connection $db
56
     */
57
    public function setDb($db)
58
    {
59
        $this->_db = $db;
60
    }
61
62
    /**
63
     * @inheritdoc
64
     */
65
    public function init()
66
    {
67
        $this->_db = Instance::ensure($this->_db, Connection::class);
68
    }
69
70
    /**
71
     * @return \yii\data\ActiveDataProvider
72
     */
73
    public function getDataProvider()
74
    {
75
        return new ActiveDataProvider([
76
            'db' => $this->_db,
77
            'query' => Banner::find()->with('translations'),
78
        ]);
79
    }
80
81
    /**
82
     * @param int $id
83
     * @return Banner
84
     * @throws NotFoundHttpException
85
     */
86
    private function findModel($id)
87
    {
88
        if ($model = Banner::findOne($id)) {
0 ignored issues
show
Bug Compatibility introduced by
The expression \ymaker\banner\backend\m...s\Banner::findOne($id); of type yii\db\ActiveRecordInterface|array|null adds the type array to the return on line 89 which is incompatible with the return type documented by ymaker\banner\backend\se...annerService::findModel of type ymaker\banner\backend\models\entities\Banner.
Loading history...
89
            return $model;
90
        }
91
        throw new NotFoundHttpException();
92
    }
93
94
    /**
95
     * Returns primary model object.
96
     *
97
     * @param null|int $id
98
     * @return Banner
99
     * @throws NotFoundHttpException
100
     */
101
    public function getModel($id = null)
102
    {
103
        if ($id === null) {
104
            $model = new Banner();
105
            $model->loadDefaultValues();
106
            $this->_model = $model;
107
        } else {
108
            $this->_model = $this->findModel($id);
109
        }
110
111
        return $this->_model;
112
    }
113
114
    /**
115
     * Save uploaded file to file system.
116
     *
117
     * @param BannerTranslation $model
118
     * @return string
119
     * @throws FileUploadException
120
     */
121
    private function saveUploadedFile($model)
122
    {
123
        $uploadedFile = UploadedFile::getInstance($model, 'imageFile');
124
        if ($uploadedFile === null) {
125
            return $model->file_name;
126
        }
127
128
        $fileName = $this->_fileManager->generateFileName($uploadedFile->extension);
129
        if ($uploadedFile->saveAs($this->_fileManager->getImageSrc($fileName))) {
130
            if (!$model->getIsNewRecord()) {
131
                $this->_fileManager->deleteFile($model->file_name);
132
            }
133
            return $fileName;
134
        }
135
136
        throw new FileUploadException('Error code #' . $uploadedFile->error);
137
    }
138
139
    /**
140
     * Save banner to database.
141
     *
142
     * @param array $data
143
     * @throws FileUploadException
144
     * @throws \DomainException
145
     * @throws \RuntimeException
146
     */
147
    protected function saveInternal(array $data)
148
    {
149
        if (!$this->_model->load($data)) {
150
            throw new \DomainException('Cannot load data to primary model');
151
        }
152
        foreach ($data[BannerTranslation::internalFormName()] as $language => $dataSet) {
153
            $model = $this->_model->getTranslation($language);
154
            $model->file_name = $this->saveUploadedFile($model);
155
            foreach ($dataSet as $attribute => $translation) {
156
                $model->$attribute = $translation;
157
            }
158
        }
159
160
        if (!$this->_model->save()) {
161
            throw new \RuntimeException();
162
        }
163
    }
164
165
    /**
166
     * Save banner and log exceptions.
167
     *
168
     * @param array $data
169
     * @return bool
170
     */
171
    public function save(array $data)
172
    {
173
        try {
174
            $this->saveInternal($data);
175
            return true;
176
        } catch (\Exception $ex) {
177
            Yii::$app->getErrorHandler()->logException($ex);
178
        }
179
180
        return false;
181
    }
182
183
    /**
184
     * Removes banner.
185
     *
186
     * @param int $id
187
     * @return bool
188
     * @throws NotFoundHttpException
189
     */
190
    public function delete($id)
191
    {
192
        $model = $this->findModel($id);
193
        try {
194
            foreach ($model->translations as $translation) {
195
                if (!$this->_fileManager->deleteFile($translation->file_name)) {
196
                    Yii::trace('Cannot delete "' . $translation->file_name . '" file', 'yii2-banner');
197
                }
198
            }
199
            return (bool)$model->delete();
200
        } catch (\Exception $ex) {
201
            Yii::$app->getErrorHandler()->logException($ex);
202
        }
203
204
        return false;
205
    }
206
}
207