PropertyTerm::addTerm()   B
last analyzed

Complexity

Conditions 6
Paths 17

Size

Total Lines 33

Duplication

Lines 7
Ratio 21.21 %

Importance

Changes 0
Metric Value
dl 7
loc 33
rs 8.7697
c 0
b 0
f 0
cc 6
nc 17
nop 2
1
<?php
2
/**
3
 * Date: 03.02.2015
4
 * Time: 09:25 ч.
5
 * @author Nikola Kostadinov
6
 */
7
8
namespace nkostadinov\taxonomy\components\terms;
9
10
use nkostadinov\taxonomy\models\TaxonomyDef;
11
use nkostadinov\taxonomy\models\TaxonomyTerms;
12
use yii\db\Exception;
13
use yii\db\Migration;
14
use yii\db\Query;
15
use yii\db\Schema;
16
use yii\helpers\ArrayHelper;
17
18
class PropertyTerm extends BaseTerm
19
{
20
    public $templateFile = '@nkostadinov/taxonomy/migrations/template/properties.php' ;
21
22
    public $updateOnExist = true;
23
24
    public function install()
25
    {
26
        parent::install();
27
28
        $migration = new Migration();
29
        $migration->createTable($this->getTable(), [
30
            'id' => Schema::TYPE_PK,
31
            'object_id' => Schema::TYPE_INTEGER,
32
            'term_id' => Schema::TYPE_BIGINT,
33
            'value' => Schema::TYPE_STRING,
34
        ]);
35
        if ($migration->db->driverName === 'mysql') {
36
            $migration->addForeignKey('fk_' . $this->getTable() . '_' . $this->getRefTableName(), $this->getTable(), 'object_id', $this->getRefTableName(), 'id', 'CASCADE');
37
            $migration->addForeignKey('fk_' . $this->getTable() . '_' . TaxonomyTerms::tableName(), $this->getTable(), 'term_id', TaxonomyTerms::tableName(), 'id', 'CASCADE');
38
        }
39
    }
40
41
    public function addTerm($object_id, $params)
42
    {
43
        foreach($params as $item => $value) {
44
            $term = TaxonomyTerms::findOne(['term' => $item, 'taxonomy_id' => $this->id]);
45 View Code Duplication
            if (!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...
46
                $term = new TaxonomyTerms();
47
                $term->taxonomy_id = $this->id;
48
                $term->term = $item;
49
                $term->total_count = 0;
50
                $term->save();
51
            }
52
            $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...
53
            $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...
54
55
            $query = new Query();
56
            if (!$query->from($this->getTable())->where($data)->exists($this->getDb())) {
57
                $transaction = $this->getDb()->beginTransaction();
58
                try {
59
                    $data['value'] = $value;
60
                    $this->getDb()->createCommand()->insert($this->getTable(), $data)->execute();
61
62
                    $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...
63
                    TaxonomyDef::updateAllCounters(['total_count' => 1], ['id' => $this->id]);
64
65
                    $transaction->commit();
66
                } catch (Exception $e) {
67
                    $transaction->rollBack();
68
                }
69
            } elseif($this->updateOnExist) {
70
                $this->getDb()->createCommand()->update($this->getTable(), ['value' => $value], $data)->execute();
71
            }
72
        }
73
    }
74
75
    public function removeTerm($object_id, $params = [])
76
    {
77
        $terms = $this->getTerms($object_id, $params);
78 View Code Duplication
        foreach($terms as $term => $value) {
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...
79
            $term = $this->getTaxonomyTerm($term);
80
            $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...
81
            $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...
82
83
            $query = new Query();
84
            if ($query->from($this->getTable())->where($data)->exists($this->getDb())) {
85
                $this->getDb()->createCommand()->delete($this->getTable(), $data)->execute();
86
87
                $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...
88
                TaxonomyDef::updateAllCounters(['total_count' => -1], [ 'id' => $this->id ]);
89
            }
90
        }
91
    }
92
93
    public function getTerms($object_id = null, $name = [])
94
    {
95
        $query = (new Query())
96
            ->select(TaxonomyTerms::tableName() . '.term, ' . $this->getTable() . '.value')
97
            ->from(TaxonomyTerms::tableName())
98
            ->innerJoin($this->getTable(), $this->getTable() . '.term_id = taxonomy_terms.id and ' . $this->getTable() . '.object_id=:object_id',
99
                [':object_id' => $object_id])
100
            ->andFilterWhere([TaxonomyTerms::tableName() . '.term' => $name]);
101
102
        return ArrayHelper::map($query->all(), 'term', 'value');
103
    }
104
}
105