|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace app\core\services; |
|
4
|
|
|
|
|
5
|
|
|
use app\core\helpers\ArrayHelper; |
|
6
|
|
|
use app\core\models\Rule; |
|
7
|
|
|
use app\core\types\RuleStatus; |
|
8
|
|
|
use yii\db\Exception; |
|
9
|
|
|
use yii\web\NotFoundHttpException; |
|
10
|
|
|
use yiier\helpers\Setup; |
|
11
|
|
|
|
|
12
|
|
|
class RuleService |
|
13
|
|
|
{ |
|
14
|
|
|
/** |
|
15
|
|
|
* @param int $id |
|
16
|
|
|
* @return Rule |
|
17
|
|
|
* @throws NotFoundHttpException |
|
18
|
|
|
* @throws Exception |
|
19
|
|
|
*/ |
|
20
|
|
|
public function copy(int $id): Rule |
|
21
|
|
|
{ |
|
22
|
|
|
$model = $this->findCurrentOne($id); |
|
23
|
|
|
$rule = new Rule(); |
|
24
|
|
|
$values = $model->toArray(); |
|
25
|
|
|
$rule->load($values, ''); |
|
26
|
|
|
$rule->name = $rule->name . ' Copy'; |
|
27
|
|
|
if (!$rule->save(false)) { |
|
28
|
|
|
throw new Exception(Setup::errorMessage($rule->firstErrors)); |
|
29
|
|
|
} |
|
30
|
|
|
return Rule::findOne($rule->id); |
|
|
|
|
|
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* @param int $id |
|
35
|
|
|
* @param string $status |
|
36
|
|
|
* @return Rule |
|
37
|
|
|
* @throws Exception |
|
38
|
|
|
* @throws NotFoundHttpException |
|
39
|
|
|
*/ |
|
40
|
|
|
public function updateStatus(int $id, string $status) |
|
41
|
|
|
{ |
|
42
|
|
|
$model = $this->findCurrentOne($id); |
|
43
|
|
|
$model->load($model->toArray(), ''); |
|
44
|
|
|
$model->status = $status; |
|
45
|
|
|
if (!$model->save(false)) { |
|
46
|
|
|
throw new Exception(Setup::errorMessage($model->firstErrors)); |
|
47
|
|
|
} |
|
48
|
|
|
return $model; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* @param string $desc |
|
54
|
|
|
* @return Rule[] |
|
55
|
|
|
*/ |
|
56
|
|
|
public function getRulesByDesc(string $desc) |
|
57
|
|
|
{ |
|
58
|
|
|
$models = Rule::find() |
|
59
|
|
|
->where(['user_id' => \Yii::$app->user->id, 'status' => RuleStatus::ACTIVE]) |
|
60
|
|
|
->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC]) |
|
61
|
|
|
->all(); |
|
62
|
|
|
$rules = []; |
|
63
|
|
|
/** @var Rule $model */ |
|
64
|
|
|
foreach ($models as $model) { |
|
65
|
|
|
if (ArrayHelper::strPosArr($desc, explode(',', $model->if_keywords)) !== false) { |
|
|
|
|
|
|
66
|
|
|
array_push($rules, $model); |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
return $rules; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
/** |
|
73
|
|
|
* @param int $id |
|
74
|
|
|
* @return Rule|object |
|
75
|
|
|
* @throws NotFoundHttpException |
|
76
|
|
|
*/ |
|
77
|
|
|
public function findCurrentOne(int $id): Rule |
|
78
|
|
|
{ |
|
79
|
|
|
if (!$model = Rule::find()->where(['id' => $id, 'user_id' => \Yii::$app->user->id])->one()) { |
|
80
|
|
|
throw new NotFoundHttpException('No data found'); |
|
81
|
|
|
} |
|
82
|
|
|
return $model; |
|
|
|
|
|
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
|