Completed
Pull Request — master (#8)
by
unknown
03:08
created

BaseTerm::listTerms()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 10
rs 9.4285
cc 1
eloc 7
nc 1
nop 0
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\Object;
17
use yii\db\Connection;
18
use yii\db\Query;
19
use yii\helpers\ArrayHelper;
20
21
abstract class BaseTerm extends Object 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);
0 ignored issues
show
Coding Style introduced by
The abstract declaration must precede the visibility declaration
Loading history...
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]);
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();
0 ignored issues
show
Unused Code Comprehensibility introduced by
79% 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...
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...
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...
119
        {
120
            $term = new TaxonomyTerms();
121
            $term->taxonomy_id = $this->id;
122
            $term->term = $name;
123
            $term->total_count = 0;
124
            $term->save();
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);
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% 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...
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
}