Completed
Push — master ( 414d92...35a2e4 )
by Nikola
02:39
created

Migrator::removeTaxonomy()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 2
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 17 and the first side effect is on line 17.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
namespace nkostadinov\taxonomy\controllers;
4
5
use nkostadinov\taxonomy\models\TaxonomyTerms;
6
use Yii;
7
use nkostadinov\taxonomy\models\TaxonomyDef;
8
use nkostadinov\taxonomy\models\TaxonomyDefSearch;
9
use yii\base\InvalidConfigException;
10
use yii\data\ActiveDataProvider;
11
use yii\helpers\Url;
12
use yii\web\Controller;
13
use yii\web\NotFoundHttpException;
14
use yii\filters\VerbFilter;
15
16
// fcgi doesn't have STDIN and STDOUT defined by default
17
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
18
defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
19
20
class Migrator extends \yii\console\controllers\MigrateController
21
{
22
    public function __construct($id, $module, $config = [])
23
    {
24
        parent::__construct($id, $module, $config); // TODO: Change the autogenerated stub
25
    }
26
27
    public function runTaxonomy($class, $migrationPath)
0 ignored issues
show
Unused Code introduced by
The parameter $migrationPath is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
28
    {
29
        ob_start();
30
        //$this->migrationPath = Yii::getAlias($migrationPath);
0 ignored issues
show
Unused Code Comprehensibility introduced by
54% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
31
        if($this->beforeAction('up'))
0 ignored issues
show
Documentation introduced by
'up' is of type string, but the function expects a object<yii\base\Action>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
32
            $this->migrateUp($class);
33
        $result = ob_get_contents();
34
        return $result;
35
    }
36
37
    public function removeTaxonomy($class, $migrationPath)
0 ignored issues
show
Unused Code introduced by
The parameter $migrationPath is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
38
    {
39
        ob_start();
40
        //$this->migrationPath = Yii::getAlias($migrationPath);
0 ignored issues
show
Unused Code Comprehensibility introduced by
54% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
41
        if($this->beforeAction('down'))
0 ignored issues
show
Documentation introduced by
'down' is of type string, but the function expects a object<yii\base\Action>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
42
            $this->migrateDown($class);
43
        $result = ob_get_contents();
44
        return $result;
45
    }
46
}
47
48
/**
49
 * DefController implements the CRUD actions for TaxonomyDef model.
50
 */
51
class DefController extends Controller
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
52
{
53
    public function behaviors()
54
    {
55
        return [
56
            'verbs' => [
57
                'class' => VerbFilter::className(),
58
                'actions' => [
59
                    'delete' => ['post'],
60
                ],
61
            ],
62
        ];
63
    }
64
65
    /**
66
     * Lists all TaxonomyDef models.
67
     * @return mixed
68
     * @throws InvalidConfigException
69
     */
70
    public function actionIndex()
71
    {
72
        if(!$this->getComponent()->isInstalled())
73
            throw new InvalidConfigException("Please run the migration first!");
74
75
        $searchModel = new TaxonomyDefSearch();
76
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
77
78
        return $this->render('index', [
79
            'searchModel' => $searchModel,
80
            'dataProvider' => $dataProvider,
81
        ]);
82
    }
83
84
    /**
85
     * Displays a single TaxonomyDef model.
86
     * @param integer $id
87
     * @return mixed
88
     */
89
    public function actionView($id)
90
    {
91
        $termProvider = new ActiveDataProvider([
92
            'query' => TaxonomyTerms::find()->andFilterWhere(['taxonomy_id' => $id]),
93
            'sort' => [
94
                // Set the default sort by name ASC and created_at DESC.
95
                'defaultOrder' => [
96
                    'total_count' => SORT_DESC,
97
                ]
98
            ],
99
        ]);
100
101
        return $this->render('view', [
102
            'model' => $this->findModel($id),
103
            'termProvider' => $termProvider
104
        ]);
105
    }
106
107
    /**
108
     * Creates a new TaxonomyDef model.
109
     * If creation is successful, the browser will be redirected to the 'view' page.
110
     * @return mixed
111
     */
112
    public function actionCreate()
113
    {
114
        $model = new TaxonomyDef();
115
        $definitions = $this->getComponent()->getDefinitions();
116
117
        if ($model->load(Yii::$app->request->post())) {
118
            //install the term
119
            $term = Yii::createObject($model->attributes);
120
                //$this->getComponent()->getTerm($model->name);
0 ignored issues
show
Unused Code Comprehensibility introduced by
77% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
121
            $term->install();
122
            $migration = new Migrator('migrate', Yii::$app);
123
            $messsage = $migration->runTaxonomy($term->migration, $term->migrationPath);
124
            Yii::$app->session->setFlash('info', $messsage, true);
125
126
            return $this->redirect(['index', 'id' => $model->id]);
127
        } else {
128
            return $this->render('create', [
129
                'model' => $model,
130
                'definitions' => $definitions,
131
            ]);
132
        }
133
    }
134
135
    /**
136
     * Updates an existing TaxonomyDef model.
137
     * If update is successful, the browser will be redirected to the 'view' page.
138
     * @param integer $id
139
     * @return mixed
140
     */
141
    public function actionUpdate($id)
142
    {
143
        $model = $this->findModel($id);
144
        $definitions = $this->getComponent()->getDefinitions();
145
146
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
147
            return $this->redirect(['view', 'id' => $model->id]);
148
        } else {
149
            return $this->render('update', [
150
                'model' => $model,
151
                'definitions' => $definitions,
152
            ]);
153
        }
154
    }
155
156
    /**
157
     * Deletes an existing TaxonomyDef model.
158
     * If deletion is successful, the browser will be redirected to the 'index' page.
159
     * @param integer $id
160
     * @return mixed
161
     */
162
    public function actionDelete($id)
163
    {
164
        $model = $this->findModel($id);
165
        //UNinstall the term
166
        $term = $this->getComponent()->getTerm($model->name);
167
        $migration = new Migrator('migrate', Yii::$app);
168
        $messsage = $migration->removeTaxonomy($term->migration, $term->migrationPath);
169
        Yii::$app->session->setFlash('info', $messsage, true);
170
171
        $term->uninstall();
172
173
174
        return $this->redirect(['index']);
175
    }
176
177
    /**
178
     * Finds the TaxonomyDef model based on its primary key value.
179
     * If the model is not found, a 404 HTTP exception will be thrown.
180
     * @param integer $id
181
     * @return TaxonomyDef the loaded model
182
     * @throws NotFoundHttpException if the model cannot be found
183
     */
184
    protected function findModel($id)
185
    {
186
        if (($model = TaxonomyDef::findOne($id)) !== null) {
187
            return $model;
188
        } else {
189
            throw new NotFoundHttpException('The requested page does not exist.');
190
        }
191
    }
192
193
    public function getComponent()
194
    {
195
        if(\Yii::$app->has($this->module->component))
0 ignored issues
show
Bug introduced by
The property component does not seem to exist. Did you mean _components?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
196
            return \Yii::$app->{$this->module->component};
0 ignored issues
show
Bug introduced by
The property component does not seem to exist. Did you mean _components?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
197
        else
198
            throw new InvalidConfigException("Cannot find taxonomy component({$this->module->component})");
0 ignored issues
show
Bug introduced by
The property component does not seem to exist. Did you mean _components?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
199
    }
200
201
    public function actionInstall()
202
    {
203
        if(!$this->getComponent()->isInstalled() and \Yii::$app->request->isPost) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
204
            //start installation
205
            if($this->getComponent()) {
206
                $this->getComponent()->install();
207
208
                $this->redirect(['/'.$this->module->id . '/' . $this->id . '/index']);
209
            } else
210
                throw new InvalidConfigException("Cannot find taxonomy component({$this->module->component})");
0 ignored issues
show
Bug introduced by
The property component does not seem to exist. Did you mean _components?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
211
        }
212
        return $this->render('install');
213
    }
214
215
    public function actionInstallterm($term)
216
    {
217
        $term = $this->getComponent()->getTerm($term);
218
        $term->install();
219
    }
220
}
221