HasTaxonomies   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 88
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 88
rs 10
wmc 8

5 Methods

Rating   Name   Duplication   Size   Complexity  
A term() 0 5 1
A scopeByTaxonomies() 0 12 4
A scopeTermsByVocabulary() 0 4 1
A terms() 0 5 1
A termsByVocabulary() 0 3 1
1
<?php
2
3
namespace Fomvasss\Taxonomy\Models\Traits;
4
5
use Fomvasss\Taxonomy\Models\Term;
6
7
/**
8
 * Трейт для пользовательских классов-моделей котории имею таксономию (статьи, товары,...)
9
 *
10
 * Trait HasTaxonomies
11
 *
12
 * @package App\Models\Traits
13
 */
14
trait HasTaxonomies
15
{
16
    /**
17
     * Связь:
18
     * Сущность текущей модели "относится" к разным термам.
19
     *
20
     * @return \Illuminate\Database\Eloquent\Relations\MorphToMany
21
     */
22
    public function terms()
23
    {
24
        $related = config('taxonomy.models.term', Term::class);
0 ignored issues
show
Bug introduced by
The function config was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

24
        $related = /** @scrutinizer ignore-call */ config('taxonomy.models.term', Term::class);
Loading history...
25
26
        return $this->morphToMany($related, 'termable');
0 ignored issues
show
Bug introduced by
It seems like morphToMany() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

26
        return $this->/** @scrutinizer ignore-call */ morphToMany($related, 'termable');
Loading history...
27
    }
28
    
29
    /**
30
     * Связь текущей модели с термамы по указанному system_name словаря.
31
     * Используется для создание связей с термамы нужного словаря в пользовательских моделях.
32
     *
33
     * @param $vocabulary
34
     * @param string|null $vocabularyKey
35
     * @return mixed
36
     */
37
    public function termsByVocabulary($vocabulary)
38
    {
39
        return $this->terms()->where('vocabulary', $vocabulary);
40
    }
41
42
    /**
43
     * Термы текущей модели по указанному system_name словаря.
44
     *
45
     * @param $query
46
     * @param $vocabulary
47
     * @param string $vocabularyKey
48
     * @return \Illuminate\Database\Eloquent\Builder|static
49
     */
50
    public function scopeTermsByVocabulary($query, $vocabulary)
51
    {
52
        return $query->whereHas('terms', function ($t) use ($vocabulary) {
53
            $t->where('vocabulary', $vocabulary);
54
        });
55
    }
56
57
    /**
58
     * Сущности по указанным термам с соответствующих
59
     * указанных словарей, например:
60
     * получить все Статьи терма-категории "WEB-Программирование" (23) с словаря "Категории статтей" И 
61
     * терма-города "Киев" (35) или "Москва" (56) с словаря "Города"
62
     *
63
     * @param $query
64
     * @param array $taxonomies Например:
65
     *  [
66
     *      'article_categories' => 23,
67
     *      'cities' => [35, 56]
68
     *  ]
69
     * @param string $termKey
70
     * @param string $vocabularyKey
71
     * @return mixed
72
     */
73
    public function scopeByTaxonomies($query, array $taxonomies, string $termKey = 'id')
74
    {
75
        foreach ($taxonomies as $vocabulary => $terms) {
76
            $terms = is_array($terms) ? $terms : [$terms];
77
            if (! empty($terms)) {
78
                $query->whereHas('terms', function ($t) use ($vocabulary, $terms, $termKey) {
79
                    $t->where('vocabulary', $vocabulary)->whereIn($termKey, $terms);
80
                });
81
            }
82
        }
83
84
        return $query;
85
    }
86
87
88
    /**
89
     * Связь:
90
     * Сущность текущая модель "имеет" один терм.
91
     * Ключ для связи находится в таблице сущности (Ex.: articles.term_id)
92
     *
93
     * @param null $foreignKey
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $foreignKey is correct as it would always require null to be passed?
Loading history...
94
     * @param null $ownerKey
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $ownerKey is correct as it would always require null to be passed?
Loading history...
95
     * @return mixed
96
     */
97
    public function term($foreignKey = null, $ownerKey = null, $relation = null)
98
    {
99
        $related = config('taxonomy.models.term', Term::class);
0 ignored issues
show
Bug introduced by
The function config was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

99
        $related = /** @scrutinizer ignore-call */ config('taxonomy.models.term', Term::class);
Loading history...
100
101
        return $this->belongsTo($related, $foreignKey, $ownerKey, $relation);
0 ignored issues
show
Bug introduced by
It seems like belongsTo() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

101
        return $this->/** @scrutinizer ignore-call */ belongsTo($related, $foreignKey, $ownerKey, $relation);
Loading history...
102
    }
103
}
104