Completed
Push — master ( 4ac004...470d43 )
by Gabriel
06:41
created

HasAndBelongsToMany   A

Complexity

Total Complexity 34

Size/Duplication

Total Lines 278
Duplicated Lines 3.24 %

Coupling/Cohesion

Components 1
Dependencies 13

Test Coverage

Coverage 15.65%

Importance

Changes 0
Metric Value
wmc 34
lcom 1
cbo 13
dl 9
loc 278
ccs 18
cts 115
cp 0.1565
rs 9.68
c 0
b 0
f 0

20 Methods

Rating   Name   Duplication   Size   Complexity  
A addParams() 0 5 1
A newQuery() 0 26 5
A getJoinFields() 0 8 2
A setJoinFields() 0 4 1
A initJoinFields() 0 5 1
A populateQuerySpecific() 9 9 1
A getLinkQuery() 0 11 2
A getEagerResults() 0 22 4
A save() 0 7 1
A deleteConnections() 0 10 1
A newDeleteQuery() 0 6 1
A saveConnections() 0 9 2
A newInsertQuery() 0 6 1
A queryAttachRecords() 0 14 5
A formatAttachData() 0 8 1
A attach() 0 7 1
A detach() 0 7 1
A queryDetachRecords() 0 13 1
A getWithClass() 0 4 1
A getDictionaryKey() 0 4 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
namespace Nip\Records\Relations;
4
5
use Nip\Database\Query\AbstractQuery;
6
use Nip\Database\Query\Delete as DeleteQuery;
7
use Nip\Database\Query\Insert as InsertQuery;
8
use Nip\Database\Query\Select as SelectQuery;
9
use Nip\HelperBroker;
10
use Nip\Records\Collections\Collection as RecordCollection;
11
use Nip\Records\Record;
12
use Nip\Records\Relations\Traits\HasPivotTable;
13
14
/**
15
 * Class HasAndBelongsToMany
16
 * @package Nip\Records\Relations
17
 */
18
class HasAndBelongsToMany extends HasOneOrMany
19
{
20
    use HasPivotTable;
21
22
    /**
23
     * @var string
24
     */
25
    protected $type = 'hasAndBelongsToMany';
26
27
    /**
28
     * @var null
29
     */
30
    protected $joinFields = null;
31
32
    /**
33
     * @inheritdoc
34
     */
35
    public function addParams($params)
36
    {
37
        parent::addParams($params);
38
        $this->addPivotParams($params);
39
    }
40
41
    /** @noinspection PhpMissingParentCallCommonInspection
42
     * @return SelectQuery
43
     * @throws \Exception
44
     */
45 1
    public function newQuery()
46
    {
47 1
        $query = $this->getDB()->newSelect();
48
49 1
        $query->from($this->getWith()->getFullNameTable());
0 ignored issues
show
Unused Code introduced by
The call to AbstractQuery::from() has too many arguments starting with $this->getWith()->getFullNameTable().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
50 1
        $query->from($this->getDB()->getDatabase() . '.' . $this->getTable());
0 ignored issues
show
Unused Code introduced by
The call to AbstractQuery::from() has too many arguments starting with $this->getDB()->getDatab...'.' . $this->getTable().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
51
52 1
        foreach ($this->getWith()->getFields() as $field) {
0 ignored issues
show
Bug introduced by
The expression $this->getWith()->getFields() of type null is not traversable.
Loading history...
53 1
            $query->cols(["{$this->getWith()->getTable()}.$field", $field]);
0 ignored issues
show
Unused Code introduced by
The call to AbstractQuery::cols() has too many arguments starting with array("{$this->getWith()...e()}.{$field}", $field).

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
54
        }
55
56 1
        foreach ($this->getJoinFields() as $field) {
0 ignored issues
show
Bug introduced by
The expression $this->getJoinFields() of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
57 1
            $query->cols(["{$this->getTable()}.$field", "__$field"]);
0 ignored issues
show
Unused Code introduced by
The call to AbstractQuery::cols() has too many arguments starting with array("{$this->getTable(...$field}", "__{$field}").

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
58
        }
59
60 1
        $this->hydrateQueryWithPivotConstraints($query);
0 ignored issues
show
Compatibility introduced by
$query of type object<Nip\Database\Query\AbstractQuery> is not a sub-type of object<Nip\Database\Query\Select>. It seems like you assume a child class of the class Nip\Database\Query\AbstractQuery to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
61
62 1
        $order = $this->getParam('order');
63 1
        if (is_array($order)) {
64
            foreach ($order as $item) {
65
                $query->order([$item[0], $item[1]]);
0 ignored issues
show
Unused Code introduced by
The call to AbstractQuery::order() has too many arguments starting with array($item[0], $item[1]).

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
66
            }
67
        }
68
69 1
        return $query;
70
    }
71
72
    /**
73
     * @return null|array
74
     */
75 1
    protected function getJoinFields()
76
    {
77 1
        if ($this->joinFields == null) {
78
            $this->initJoinFields();
79
        }
80
81 1
        return $this->joinFields;
82
    }
83
84
    /**
85
     * @param null $joinFields
86
     */
87 1
    public function setJoinFields($joinFields)
88
    {
89 1
        $this->joinFields = $joinFields;
90 1
    }
91
92
    protected function initJoinFields()
93
    {
94
        $structure = $this->getDB()->getMetadata()->describeTable($this->getTable());
95
        $this->setJoinFields(array_keys($structure["fields"]));
96
    }
97
98
    /**
99
     * @inheritdoc
100
     */
101 View Code Duplication
    public function populateQuerySpecific(AbstractQuery $query)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
102
    {
103
        $pk1 = $this->getPrimaryKey();
104
        $fk1 = $this->getFK();
105
106
        $query->where("`{$this->getTable()}`.`$fk1` = ?", $this->getItem()->{$pk1});
107
108
        return $query;
109
    }
110
111
    /**
112
     * Simple select query from the link table
113
     * @param bool $specific
114
     * @return SelectQuery
115
     */
116
    public function getLinkQuery($specific = true)
117
    {
118
        $query = $this->getDB()->newSelect();
119
        $query->from($this->getTable());
0 ignored issues
show
Unused Code introduced by
The call to AbstractQuery::from() has too many arguments starting with $this->getTable().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
120
121
        if ($specific) {
122
            $query = $this->populateQuerySpecific($query);
123
        }
124
125
        return $query;
126
    }
127
128
    /** @noinspection PhpMissingParentCallCommonInspection
129
     * @param RecordCollection $collection
130
     * @return RecordCollection
131
     */
132
    public function getEagerResults($collection)
133
    {
134
        if ($collection->count() < 1) {
135
            return $this->getWith()->newCollection();
136
        }
137
138
        $query = $this->getEagerQuery($collection);
139
140
        $return = $this->newCollection();
141
        $results = $this->getDB()->execute($query);
142
        if ($results->numRows() > 0) {
143
            $i = 1;
144
            $rows = $results->fetchResults();
145
            foreach ($rows as $row) {
146
                $row['relation_key'] = $i++;
147
                $item = $this->getWith()->getNew($row);
148
                $return->add($item, 'relation_key');
149
            }
150
        }
151
152
        return $return;
153
    }
154
155
    /** @noinspection PhpMissingParentCallCommonInspection
156
     * @return $this
157
     */
158
    public function save()
159
    {
160
        $this->deleteConnections();
161
        $this->saveConnections();
162
163
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this; (Nip\Records\Relations\HasAndBelongsToMany) is incompatible with the return type of the parent method Nip\Records\Relations\HasOneOrMany::save of type boolean.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
164
    }
165
166
    protected function deleteConnections()
167
    {
168
        $query = $this->newDeleteQuery();
169
        $query->where(
170
            "{$this->getFK()} = ?",
171
            $this->getItemRelationPrimaryKey()
172
        );
173
//        echo $query;
174
        $query->execute();
175
    }
176
177
    /**
178
     * @return DeleteQuery
179
     */
180
    protected function newDeleteQuery()
181
    {
182
        $query = $this->getDB()->newDelete();
183
        $query->table($this->getTable());
184
        return $query;
185
    }
186
187
    protected function saveConnections()
188
    {
189
        if ($this->hasResults()) {
190
            $query = $this->newInsertQuery();
191
            $this->queryAttachRecords($query, $this->getResults());
192
//            echo $query;
193
            $query->execute();
194
        }
195
    }
196
197
    /**
198
     * @return InsertQuery
199
     */
200
    protected function newInsertQuery()
201
    {
202
        $query = $this->getDB()->newInsert();
203
        $query->table($this->getTable());
204
        return $query;
205
    }
206
207
    /**
208
     * @param InsertQuery $query
209
     * @param $records
210
     */
211
    protected function queryAttachRecords($query, $records)
212
    {
213
        foreach ($records as $record) {
214
            $data = $this->formatAttachData($record);
215
            foreach ($this->getJoinFields() as $field) {
0 ignored issues
show
Bug introduced by
The expression $this->getJoinFields() of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
216
                if ($record->{"__$field"}) {
217
                    $data[$field] = $record->{"__$field"};
218
                } else {
219
                    $data[$field] = $data[$field] ? $data[$field] : false;
220
                }
221
            }
222
            $query->data($data);
0 ignored issues
show
Unused Code introduced by
The call to Insert::data() has too many arguments starting with $data.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
223
        }
224
    }
225
226
    /**
227
     * @param $record
228
     * @return array
229
     */
230
    protected function formatAttachData($record)
231
    {
232
        $data = [
233
            $this->getManager()->getPrimaryFK() => $this->getItem()->{$this->getManager()->getPrimaryKey()},
234
            $this->getPivotFK() => $record->{$this->getWith()->getPrimaryKey()},
235
        ];
236
        return $data;
237
    }
238
239
    /**
240
     * @param $model
241
     */
242
    public function attach($model)
243
    {
244
        $query = $this->newInsertQuery();
245
        $this->queryAttachRecords($query, [$model]);
246
//            echo $query;
247
        $query->execute();
248
    }
249
250
    /**
251
     * @param Record $model
252
     */
253
    public function detach($model)
254
    {
255
        $query = $this->newDeleteQuery();
256
        $this->queryDetachRecords($query, [$model]);
257
//        echo $query;
258
        $query->execute();
259
    }
260
261
    /**
262
     * @param DeleteQuery $query
263
     * @param $records
264
     */
265
    protected function queryDetachRecords($query, $records)
266
    {
267
        $ids = HelperBroker::get('Arrays')->pluck($records, $this->getWith()->getPrimaryKey());
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Nip\Helpers\AbstractHelper as the method pluck() does only exist in the following sub-classes of Nip\Helpers\AbstractHelper: Nip_Helper_Arrays. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
268
        $query->where(
269
            "{$this->getPivotFK()} IN ?",
270
            $ids
271
        );
272
273
        $query->where(
274
            "{$this->getFK()} = ?",
275
            $this->getItemRelationPrimaryKey()
276
        );
277
    }
278
279
280
    /** @noinspection PhpMissingParentCallCommonInspection
281
     * @return mixed
282
     */
283
    public function getWithClass()
284
    {
285
        return $this->getName();
286
    }
287
288
    /** @noinspection PhpMissingParentCallCommonInspection
289
     * @return string
290
     */
291
    protected function getDictionaryKey()
292
    {
293
        return '__' . $this->getFK();
294
    }
295
}
296