Completed
Push — development ( c8f467...de45b7 )
by Andrij
10:53
created

Star_rating::show_star_rating()   C

Complexity

Conditions 9
Paths 34

Size

Total Lines 63
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 9
eloc 45
c 4
b 0
f 0
nc 34
nop 2
dl 0
loc 63
rs 6.6149

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
use CMSFactory\assetManager;
4
5
if (!defined('BASEPATH')) {
6
    exit('No direct script access allowed');
7
}
8
9
/**
10
 * Image CMS
11
 *
12
 * In oder to show "Star rating" type in template:
13
 * {$CI->load->module('star_rating')->show_star_rating()}
14
 *
15
 * If you want to show "Star rating" for product
16
 * {$CI->load->module('star_rating')->show_star_rating(SProducts $product)}
17
 *
18
 * More turn on autoload and url access.
19
 *
20
 * Star rating module
21
 *
22
 * @property Rating_model rating_model
23
 */
24
class Star_rating extends MY_Controller
25
{
0 ignored issues
show
introduced by
Opening brace of a class must be on the same line as the definition
Loading history...
26
27
    private $new_votes = 0;
28
29
    private $new_rating = 0;
30
31
    private $list_for_show = [
32
                              'main',
33
                              'category',
34
                              'brand',
35
                              'product',
36
                              'shop_category',
37
                              'page',
38
                             ];
39
40
    public function __construct() {
41
42
        parent::__construct();
43
        $this->load->helper('path');
44
        $this->load->model('rating_model');
45
        $obj = new MY_Lang();
46
        $obj->load('star_rating');
47
    }
48
49
    public static function adminAutoload() {
50
51
        parent::adminAutoload();
52
    }
53
54
    public function autoload() {
55
56
    }
57
58
    /**
59
     * Show star_rating
60
     * @param SProducts $item
0 ignored issues
show
Documentation introduced by
Should the type for parameter $item not be SProducts|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
61
     * @param bool $registerScript
62
     * @return $this|bool
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use false|Star_rating.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
introduced by
@return data type must not contain "$"
Loading history...
63
     */
64
    public function show_star_rating($item = null, $registerScript = true) {
65
        $this->list_for_show = $this->rating_model->get_settings();
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->rating_model->get_settings() can also be of type null or string. However, the property $list_for_show is declared as type array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
66
        if ($this->list_for_show == null) {
67
            $this->list_for_show = [];
68
        }
69
        $id = $this->core->core_data['id'];
70
        $type = $this->core->core_data['data_type'];
71
72
        // product rating
73
        if ($item != null && $item instanceof SProducts) {
0 ignored issues
show
Bug introduced by
The class SProducts does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
74
            if ($item->getRating() != null) {
75
                $rating_s = (int) $item->getRating() * 20; // rating in percent
76
            } else {
77
                $rating_s = 0;
78
            }
79
80
            /** Берем все комментарии по данному товару*/
81
            $count_commment = $this->db->select('rate')
82
                ->from('comments')
83
                ->where('item_id', $item->getId())
84
                ->count_all_results();
85
86
            $data = [
87
                     'id_type' => $item->getId(),
88
                     'type'    => 'product',
89
                     'votes'   => $count_commment,
90
                     'rating'  => $rating_s,
91
                    ];
92
            $template = 'product_star_rating';
93
        } else {
94
            if (in_array($type, array_keys($this->list_for_show))) {
95
                $rating = $this->rating_model->get_rating($id, $type);
96
                if ($rating->votes != 0) {
97
                    $rating_s = $rating->rating / $rating->votes * 20; //rating in percent
98
                } else {
99
                    $rating_s = 0;
100
                }
101
                $data = [
102
                         'id'     => $rating->id,
103
                         'type'   => $rating->type,
104
                         'votes'  => $rating->votes,
105
                         'rating' => $rating_s,
106
                        ];
107
108
                $template = 'star_rating';
109
            } else {
110
                $template = null;
0 ignored issues
show
Unused Code introduced by
$template is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
111
                return false;
112
            }
113
        }
114
115
        //Show template with prepared parameters
116
        if ($template !== null) {
117
            $renderTemplate = assetManager::create();
118
        }
119
        $renderTemplate->setData($data)
120
            ->registerStyle('style');
121
        if ($registerScript) {
122
            $renderTemplate->registerScript('scripts');
123
        }
124
        $renderTemplate->render($template, true);
125
        return $this;
126
    }
127
128
    /**
129
     * Change rating for pages / product
130
     * @return string|null
131
     */
132
    public function ajax_rate() {
133
134
        $id = $this->input->post('cid');
135
        $type = $this->input->post('type');
136
        $rating = (int) $this->input->post('val');
137
138
        if ($id != null && $type != null && !$this->session->userdata('voted_g' . $id . $type) == true) {
139
            //Check if rating exists
140
            $check = $this->rating_model->get_rating($id, $type);
141
            if ($check != null) {
142
                $this->new_votes = $check->votes + 1;
143
                $this->new_rating = $check->rating + $rating;
144
                $data = [
145
                         'votes'  => $this->new_votes,
146
                         'rating' => $this->new_rating,
147
                        ];
148
                $rating_res = $this->new_rating / $this->new_votes * 20;
149
                $votes_res = $this->new_votes;
150
                $this->rating_model->update_rating($id, $type, $data);
151
            } else {
152
                $data = [
153
                         'id_type' => $id,
154
                         'type'    => $type,
155
                         'votes'   => 1,
156
                         'rating'  => $rating,
157
                        ];
158
                $votes_res = 1;
159
                $rating_res = $rating * 20;
160
                $this->rating_model->insert_rating($data);
161
            }
162
            //Change rating for product
163
            if ($type == 'product') {
164
                if (SProductsQuery::create()->findPk($id) !== null) {
165
                    $model = SProductsRatingQuery::create()->findPk($id);
166
                    if ($model === null) {
167
                        $model = new SProductsRating;
0 ignored issues
show
Coding Style introduced by
Instantiating objects should always be done with parentheses.

The object instantiation should always have parentheses even if no arguments are passed:

new DateTime; // Bad
new DateTime(); // Good
Loading history...
168
                        $model->setProductId($id);
169
                    }
170
                    $rating_res = (($model->getRating() + $rating) / ($model->getVotes() + 1)) * 20;
171
                    $votes_res = $model->getVotes() + 1;
172
173
                    $model->setVotes($model->getVotes() + 1);
174
                    $model->setRating($model->getRating() + $rating);
175
                    $model->save();
176
                }
177
            }
178
            //Save in session user's info
179
            $this->session->set_userdata('voted_g' . $id . $type, true);
180
181
            //If ajax request than return data for with new rating and votes
182
            if ($this->input->is_ajax_request()) {
183
                return json_encode(
184
                    [
185
                     'rate'  => "$rating_res",
186
                     'votes' => "$votes_res",
187
                    ]
188
                );
189
            }
190
        } else {
191
            return json_encode(['rate' => null]);
192
        }
193
    }
194
195
    /**
196
     * Install module
197
     */
198 View Code Duplication
    public function _install() {
199
200
        $this->load->dbforge();
201
        ($this->dx_auth->is_admin()) OR exit;
202
        $fields = [
203
                   'id'      => [
204
                                 'type'           => 'INT',
205
                                 'auto_increment' => TRUE,
206
                                ],
207
                   'id_type' => [
208
                                 'type'       => 'VARCHAR',
209
                                 'constraint' => '25',
210
                                 'null'       => TRUE,
211
                                ],
212
                   'type'    => [
213
                                 'type'       => 'VARCHAR',
214
                                 'constraint' => '25',
215
                                 'null'       => TRUE,
216
                                ],
217
                   'votes'   => ['type' => 'INT'],
218
                   'rating'  => ['type' => 'INT'],
219
                  ];
220
221
        $this->dbforge->add_field($fields);
222
        $this->dbforge->add_key('id', TRUE);
223
        $this->dbforge->create_table('rating');
224
225
        $this->db->where('name', 'star_rating');
226
        $this->db->update('components', ['enabled' => 1]);
227
    }
228
229
    /**
230
     * Deinstall module
231
     */
232
    public function _deinstall() {
233
234
        $this->load->dbforge();
235
        ($this->dx_auth->is_admin()) OR exit;
236
        $this->dbforge->drop_table('rating');
237
    }
238
239
}