1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @link https://github.com/vuongxuongminh/yii2-searchable |
4
|
|
|
* @copyright Copyright (c) 2019 Vuong Xuong Minh |
5
|
|
|
* @license [New BSD License](http://www.opensource.org/licenses/bsd-license.php) |
6
|
|
|
*/ |
7
|
|
|
|
8
|
|
|
namespace vxm\searchable\console; |
9
|
|
|
|
10
|
|
|
use yii\base\InvalidArgumentException; |
11
|
|
|
use yii\console\Controller; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Class CommandController support import and flush model classes. |
15
|
|
|
* |
16
|
|
|
* @author Vuong Minh <[email protected]> |
17
|
|
|
* @since 1.0.0 |
18
|
|
|
*/ |
19
|
|
|
class CommandController extends Controller |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* @var string|null models class name separate by `,`. |
23
|
|
|
*/ |
24
|
|
|
public $models; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @inheritDoc |
28
|
|
|
*/ |
29
|
|
|
public function options($actionID) |
30
|
|
|
{ |
31
|
|
|
return array_merge(parent::options($actionID), ['models']); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @inheritDoc |
36
|
|
|
*/ |
37
|
2 |
|
public function beforeAction($action) |
38
|
|
|
{ |
39
|
2 |
|
$result = parent::beforeAction($action); |
40
|
|
|
|
41
|
2 |
|
if ($this->models === null) { |
42
|
|
|
throw new InvalidArgumentException('`models` options must be set!'); |
43
|
|
|
} |
44
|
|
|
|
45
|
2 |
|
return $result; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* Import the given models into the search index. |
50
|
|
|
*/ |
51
|
1 |
View Code Duplication |
public function actionImport() |
|
|
|
|
52
|
|
|
{ |
53
|
1 |
|
$models = explode(',', $this->models); |
54
|
1 |
|
$models = array_filter($models); |
55
|
|
|
|
56
|
1 |
|
foreach ($models as $model) { |
57
|
1 |
|
$model = trim($model); |
58
|
1 |
|
$model::makeAllSearchable(); |
59
|
|
|
|
60
|
1 |
|
$this->stdout('All [' . $model . '] records have been imported.'); |
61
|
|
|
} |
62
|
1 |
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* Delete the model class records from the index. |
66
|
|
|
*/ |
67
|
1 |
View Code Duplication |
public function actionDelete() |
|
|
|
|
68
|
|
|
{ |
69
|
1 |
|
$models = explode(',', $this->models); |
70
|
1 |
|
$models = array_filter($models); |
71
|
|
|
|
72
|
1 |
|
foreach ($models as $model) { |
73
|
1 |
|
$model = trim($model); |
74
|
1 |
|
$model::deleteAllFromSearch(); |
75
|
|
|
|
76
|
1 |
|
$this->stdout('All [' . $model . '] records have been deleted.'); |
77
|
|
|
} |
78
|
1 |
|
} |
79
|
|
|
|
80
|
|
|
|
81
|
|
|
} |
82
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.