Completed
Pull Request — master (#57)
by Olexandr
02:41
created

Record   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 209
Duplicated Lines 24.4 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 17
c 2
b 0
f 0
lcom 1
cbo 3
dl 51
loc 209
rs 10

11 Methods

Rating   Name   Duplication   Size   Complexity  
A convertToDateTime() 0 4 1
A applySorting() 0 13 2
A where() 0 6 1
A orderBy() 8 8 2
A primary() 0 4 1
A sortArrayByArray() 10 10 3
A find() 22 22 3
A fields() 0 8 1
A first() 11 11 1
A count() 0 8 1
A __construct() 0 5 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: nazarenko
5
 * Date: 29.03.2016
6
 * Time: 10:52
7
 */
8
namespace samsoncms\api\query;
9
10
use samsonframework\orm\ArgumentInterface;
11
use samsonframework\orm\Condition;
12
use samsonframework\orm\ConditionInterface;
13
use samsonframework\orm\QueryInterface;
14
15
class Record
16
{
17
    /** @var string Table class name */
18
    protected static $identifier;
19
20
    /** @var string Table primary field name */
21
    protected static $primaryFieldName;
22
23
    /** @var array Collection of all entity fields */
24
    protected static $parentFields = array();
25
26
    /** @var QueryInterface Database query instance */
27
    protected $query;
28
29
    /** @var array Collection of entity fields to retrieved from database */
30
    protected $selectedFields;
31
32
    /** @var ConditionInterface Query conditions */
33
    protected $conditions;
34
35
    /** @var array Collection of ordering parameters */
36
    protected $orderBy = array();
37
38
    /** @var array Collection of limit parameters */
39
    protected $limit = array();
40
41
    /** @var array Collection of entity identifiers */
42
    protected $entityIDs = array();
43
44
    /**
45
     * Convert date value to database format.
46
     * TODO: Must implement at database layer
47
     *
48
     * @param string $date Date value for conversion
49
     * @return string Converted date to correct format
50
     */
51
    protected function convertToDateTime($date)
52
    {
53
        return date('Y-m-d H:i:s', strtotime($date));
54
    }
55
56
    /**
57
     * Add sorting to entity identifiers.
58
     *
59
     * @param array $entityIDs
60
     * @param string $fieldName Additional field name for sorting
61
     * @param string $order Sorting order(ASC|DESC)
62
     * @return array Collection of entity identifiers ordered by additional field value
63
     */
64
    protected function applySorting(array $entityIDs, $fieldName, $order = 'ASC')
65
    {
66
        if (array_key_exists($fieldName, static::$parentFields)) {
67
            // Order by parent fields
68
            return $this->query
69
                ->entity(static::$identifier)
70
                ->where(static::$primaryFieldName, $entityIDs)
71
                ->orderBy($fieldName, $order)
72
                ->fields(static::$primaryFieldName);
73
        } else { // Nothing is changed
74
            return $entityIDs;
75
        }
76
    }
77
78
    /**
79
     * Add condition to current query.
80
     *
81
     * @param string $fieldName Entity field name
82
     * @param string $fieldValue Value
83
     * @param string $fieldRelation
84
     * @return $this Chaining
85
     */
86
    public function where($fieldName, $fieldValue = null, $fieldRelation = ArgumentInterface::EQUAL)
87
    {
88
        $this->conditions->add($fieldName, $fieldValue, $fieldRelation);
89
90
        return $this;
91
    }
92
93
    /**
94
     * Set field for sorting.
95
     *
96
     * @param string $fieldName Additional field name
97
     * @param string $order Sorting order
98
     * @return $this Chaining
99
     */
100 View Code Duplication
    public function orderBy($fieldName, $order = 'ASC')
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...
101
    {
102
        if (array_key_exists($fieldName, static::$parentFields)) {
103
            $this->orderBy = array($fieldName, $order);
104
        }
105
106
        return $this;
107
    }
108
109
    /**
110
     * Add primary field query condition.
111
     *
112
     * @param string $value Field value
113
     * @return $this Chaining
114
     * @see Material::where()
115
     */
116
    public function primary($value)
117
    {
118
        return $this->where(static::$primaryFieldName, $value);
119
    }
120
121
    /**
122
     * Reorder elements in one array according to keys of another.
123
     *
124
     * @param array $array Source array
125
     * @param array $orderArray Ideal array
126
     * @return array Ordered array
127
     */
128 View Code Duplication
    protected function sortArrayByArray(array $array, array $orderArray) {
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...
129
        $ordered = array();
130
        foreach($orderArray as $key) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FOREACH keyword; 0 found
Loading history...
131
            if(array_key_exists($key,$array)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
132
                $ordered[$key] = $array[$key];
133
                unset($array[$key]);
134
            }
135
        }
136
        return array_merge($ordered, $array);
137
    }
138
139
    /**
140
     * Perform SamsonCMS query and get entities collection.
141
     *
142
     * @return \samsoncms\api\Entity[] Collection of found entities
143
     */
144 View Code Duplication
    public function find()
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...
145
    {
146
        $this->query->entity(static::$identifier);
147
148
        // Set entity primary keys if predefined
149
        if (count($this->entityIDs)) {
150
            $this->primary($this->entityIDs);
0 ignored issues
show
Documentation introduced by
$this->entityIDs is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
151
        }
152
153
        // Add query sorter for showed page
154
        if (count($this->orderBy) === 2) {
155
            $this->query->orderBy($this->orderBy[0], $this->orderBy[1]);
156
        }
157
158
        // Proxy to regular database query
159
        $return = $this->query
160
            ->whereCondition($this->conditions)
161
            ->exec();
162
163
        // Reorder if entity identifiers collection was defined
164
        return $this->sortArrayByArray($return, $this->entityIDs);
0 ignored issues
show
Bug introduced by
It seems like $return defined by $this->query->whereCondi...is->conditions)->exec() on line 159 can also be of type boolean; however, samsoncms\api\query\Record::sortArrayByArray() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
165
    }
166
167
    /**
168
     * Perform SamsonCMS query and get collection of entities fields.
169
     *
170
     * @param string $fieldName Entity field name
171
     * @return array Collection of entity fields
172
     */
173
    public function fields($fieldName)
174
    {
175
        // Proxy to regular database query
176
        return $this->query
177
            ->entity(static::$identifier)
178
            ->whereCondition($this->conditions)
179
            ->fields($fieldName);
180
    }
181
182
    /**
183
     * Perform SamsonCMS query and get first matching entity.
184
     *
185
     * @return \samsoncms\api\Entity First matching entity
186
     */
187 View Code Duplication
    public function first()
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...
188
    {
189
        // Proxy to regular database query
190
        $return = $this->query
191
            ->entity(static::$identifier)
192
            ->limit(1)
193
            ->whereCondition($this->conditions)
194
            ->exec();
195
196
        return array_shift($return);
197
    }
198
199
    /**
200
     * Perform SamsonCMS query and get amount resulting entities.
201
     *
202
     * @return int Amount of resulting entities
203
     */
204
    public function count()
205
    {
206
        // Proxy to regular database query
207
        return $this->query
208
            ->entity(static::$identifier)
209
            ->whereCondition($this->conditions)
210
            ->count();
211
    }
212
213
    /**
214
     * Generic constructor.
215
     *
216
     * @param QueryInterface $query Database query instance
217
     */
218
    public function __construct(QueryInterface $query)
219
    {
220
        $this->query = $query;
221
        $this->conditions = new Condition();
222
    }
223
}