BaseTerm   A
last analyzed

Complexity

Total Complexity 23

Size/Duplication

Total Lines 155
Duplicated Lines 13.55 %

Coupling/Cohesion

Components 2
Dependencies 10

Importance

Changes 0
Metric Value
wmc 23
lcom 2
cbo 10
dl 21
loc 155
rs 10
c 0
b 0
f 0

15 Methods

Rating   Name   Duplication   Size   Complexity  
addTerm() 0 1 ?
A removeTerm() 13 20 4
A getTerms() 0 14 2
A setTerms() 0 7 1
A isInstalled() 0 4 1
A install() 0 4 1
A uninstall() 0 8 1
A getDb() 0 4 1
A canInstall() 0 5 2
A getTaxonomyTerm() 8 13 3
A getRefTableName() 0 7 2
A getTable() 0 4 1
A getRefTable() 0 4 1
A getMigrationFile() 0 8 2
A createMigration() 0 19 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: Nikola nb
5
 * Date: 19.10.2014
6
 * Time: 11:35 ч.
7
 */
8
9
namespace nkostadinov\taxonomy\components\terms;
10
11
use nkostadinov\taxonomy\components\interfaces\ITaxonomyTermInterface;
12
use nkostadinov\taxonomy\models\TaxonomyDef;
13
use nkostadinov\taxonomy\models\TaxonomyTerms;
14
use Yii;
15
use yii\base\Exception;
16
use yii\base\BaseObject;
17
use yii\db\Connection;
18
use yii\db\Query;
19
use yii\helpers\ArrayHelper;
20
21
abstract class BaseTerm extends BaseObject implements ITaxonomyTermInterface
22
{
23
    public $migrationPath = '@app/migrations';
24
25
    public $id;
26
    public $name; //the name of the term
27
    public $data_table;
28
    public $ref_table;
29
    public $is_multi = false;
30
    public $created_at;
31
    public $total_count;
32
    public $migration;
33
34
    public abstract function addTerm($object_id, $params);
35
36
    public function removeTerm($object_id, $params = [])
37
    {
38
        if(empty($params)) {
39
            $params = $this->getTerms($object_id);
40
        }
41
42 View Code Duplication
        foreach($params as $item) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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.

Loading history...
43
            $term = $this->getTaxonomyTerm($item);
44
            $data['term_id'] = $term->id;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
45
            $data['object_id'] = $object_id;
0 ignored issues
show
Bug introduced by
The variable $data does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
46
47
            $query = new Query();
48
            if ($query->from($this->table)->where($data)->exists($this->getDb())) {
0 ignored issues
show
Documentation introduced by
The property table does not exist on object<nkostadinov\taxon...ponents\terms\BaseTerm>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
49
                $this->getDb()->createCommand()->delete($this->table, $data)->execute();
0 ignored issues
show
Documentation introduced by
The property table does not exist on object<nkostadinov\taxon...ponents\terms\BaseTerm>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
50
51
                $term->updateCounters(['total_count' => -1]);
0 ignored issues
show
Bug introduced by
The method updateCounters() does not exist on yii\db\ActiveRecordInterface. Did you maybe mean update()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
52
                Taxonomydef::updateAllCounters(['total_count' => -1], [ 'id' => $this->id ]);
53
            }
54
        }
55
    }
56
57
    public function getTerms($object_id = null, $name = [])
58
    {
59
        $query = TaxonomyTerms::find()
60
            ->select('term')
61
            ->where(['taxonomy_id' => $this->id])
62
            ->andFilterWhere(['taxonomy_terms.term' => $name]);
63
64
        if ($object_id) {
65
            $query->innerJoin($this->table, $this->table . '.term_id = taxonomy_terms.id')
0 ignored issues
show
Documentation introduced by
The property table does not exist on object<nkostadinov\taxon...ponents\terms\BaseTerm>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
66
                  ->onCondition("$this->table.object_id = $object_id");
0 ignored issues
show
Documentation introduced by
The property table does not exist on object<nkostadinov\taxon...ponents\terms\BaseTerm>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
67
        }
68
        
69
        return ArrayHelper::getColumn($query->all(), 'term');
70
    }
71
72
    public function setTerms($object_id, $params = [])
73
    {
74
        Yii::$app->db->transaction(function() use ($object_id, $params) {
75
            $this->removeTerm($object_id);
76
            $this->addTerm($object_id, $params);
77
        });
78
    }
79
80
    public function isInstalled()
81
    {
82
        return Yii::$app->db->getTableSchema($this->getTable(), true) !== null;
83
    }
84
85
    public function install()
86
    {
87
        return $this->createMigration();
88
    }
89
90
    public function uninstall()
91
    {
92
        //drop the data table
93
        //$this->getDb()->createCommand()->dropTable($this->getTable())->execute();
94
        //delete the term itself
95
        $model = TaxonomyDef::findOne($this->id);
96
        $model->delete();
97
    }
98
99
    /**
100
     * Return the db connection component.
101
     *
102
     * @return Connection
103
     */
104
    public static function getDb()
105
    {
106
        return Yii::$app->db;
107
    }
108
109
    public function canInstall() {
110
        if(!$this->getTable())
111
            return 'Missing "table" property';
112
        return true;
113
    }
114
115
    public function getTaxonomyTerm($name, $create = true)
116
    {
117
        $term = TaxonomyTerms::findOne(['term'=>$name, 'taxonomy_id' => $this->id]);
118 View Code Duplication
        if($create and !isset($term)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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.

Loading history...
119
            $term = new TaxonomyTerms();
120
            $term->taxonomy_id = $this->id;
121
            $term->term = $name;
122
            $term->total_count = 0;
123
            $term->save();
124
        }
125
        
126
        return $term;
127
    }
128
129
    public function getRefTableName()
130
    {
131
        if(strpos($this->refTable, '\\') === FALSE) //not an AR class but a table name
0 ignored issues
show
Documentation introduced by
The property refTable does not exist on object<nkostadinov\taxon...ponents\terms\BaseTerm>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
132
            return $this->refTable;
0 ignored issues
show
Documentation introduced by
The property refTable does not exist on object<nkostadinov\taxon...ponents\terms\BaseTerm>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
133
        else
134
            return call_user_func([$this->refTable, 'tableName']);
0 ignored issues
show
Documentation introduced by
The property refTable does not exist on object<nkostadinov\taxon...ponents\terms\BaseTerm>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
135
    }
136
137
    public function getTable()
138
    {
139
        return $this->data_table;
140
    }
141
142
    public function getRefTable()
143
    {
144
        return $this->ref_table;
145
    }
146
147
    public function getMigrationFile()
148
    {
149
        if (!preg_match('/^\w+$/', $this->name)) {
150
            throw new Exception('The migration name should contain letters, digits and/or underscore characters only.');
151
        }
152
        $name = 'm' . gmdate('ymd_His') . '_' . $this->name;
153
        return $name;
154
    }
155
156
    public function createMigration()
157
    {
158
159
        $name = $this->getMigrationFile();
160
        $file = Yii::getAlias($this->migrationPath . DIRECTORY_SEPARATOR . $name . '.php');
161
162
        //$data = get_object_vars($this);
163
        $data = [];
164
        $data['name'] = $this->name;
165
        $data['class'] = get_class($this);
166
        $data['data_table'] = $this->data_table;
167
        $data['ref_table'] = $this->getRefTableName();
168
        $data['migration'] = $name;
169
170
        $this->migration = $name;
171
        $content = Yii::$app->getView()->renderFile(Yii::getAlias($this->templateFile), [ 'data' => $data ]);
0 ignored issues
show
Documentation introduced by
The property templateFile does not exist on object<nkostadinov\taxon...ponents\terms\BaseTerm>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
172
        file_put_contents($file, $content);
173
        return $name;
174
    }
175
}