Completed
Push — development ( eb9524...db4517 )
by Andrij
28:49 queued 02:09
created

Star_rating::show_star_rating()   B

Complexity

Conditions 9
Paths 34

Size

Total Lines 57
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 57
rs 7.0745
cc 9
eloc 41
nc 34
nop 2

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 = ['main', 'category', 'brand', 'product', 'shop_category', 'page'];
32
33
    public function __construct() {
34
35
        parent::__construct();
36
        $this->load->helper('path');
37
        $this->load->model('rating_model');
38
        $obj = new MY_Lang();
39
        $obj->load('star_rating');
40
    }
41
42
    public static function adminAutoload() {
43
44
        parent::adminAutoload();
45
    }
46
47
    public function autoload() {
48
49
    }
50
51
    /**
52
     * Show star_rating
53
     * @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...
54
     * @param bool $registerScript
55
     * @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...
56
     */
57
    public function show_star_rating($item = null, $registerScript = true) {
58
        $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...
59
        if ($this->list_for_show == null) {
60
            $this->list_for_show = [];
61
        }
62
        $id = $this->core->core_data['id'];
63
        $type = $this->core->core_data['data_type'];
64
65
        // product rating
66
        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...
67
            if ($item->getRating() != null) {
68
                $rating_s = (int) $item->getRating() * 20; // rating in percent
69
            } else {
70
                $rating_s = 0;
71
            }
72
73
            $data = [
74
                'id_type' => $item->getId(),
75
                'type' => 'product',
76
                'votes' => $item->getVotes(),
77
                'rating' => $rating_s
78
            ];
79
            $template = 'product_star_rating';
80
        } else {
81
            if (in_array($type, array_keys($this->list_for_show))) {
82
                $rating = $this->rating_model->get_rating($id, $type);
83
                if ($rating->votes != 0) {
84
                    $rating_s = $rating->rating / $rating->votes * 20; //rating in percent
85
                } else {
86
                    $rating_s = 0;
87
                }
88
                $data = [
89
                    'id' => $rating->id,
90
                    'type' => $rating->type,
91
                    'votes' => $rating->votes,
92
                    'rating' => $rating_s
93
                ];
94
95
                $template = 'star_rating';
96
            } else {
97
                $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...
98
                return false;
99
            }
100
        }
101
102
        //Show template with prepared parameters
103
        if ($template !== null) {
104
            $renderTemplate = assetManager::create();
105
        }
106
        $renderTemplate->setData($data)
107
            ->registerStyle('style');
108
        if ($registerScript) {
109
            $renderTemplate->registerScript('scripts');
110
        }
111
        $renderTemplate->render($template, true);
112
        return $this;
113
    }
114
115
    /**
116
     * Change rating for pages / product
117
     * @return string|null
118
     */
119
    public function ajax_rate() {
120
121
        $id = $this->input->post('cid');
122
        $type = $this->input->post('type');
123
        $rating = (int) $this->input->post('val');
124
125
        if ($id != null && $type != null && !$this->session->userdata('voted_g' . $id . $type) == true) {
126
            //Check if rating exists
127
            $check = $this->rating_model->get_rating($id, $type);
128
            if ($check != null) {
129
                $this->new_votes = $check->votes + 1;
130
                $this->new_rating = $check->rating + $rating;
131
                $data = [
132
                    'votes' => $this->new_votes,
133
                    'rating' => $this->new_rating
134
                ];
135
                $rating_res = $this->new_rating / $this->new_votes * 20;
136
                $votes_res = $this->new_votes;
137
                $this->rating_model->update_rating($id, $type, $data);
138
            } else {
139
                $data = [
140
                    'id_type' => $id,
141
                    'type' => $type,
142
                    'votes' => 1,
143
                    'rating' => $rating
144
                ];
145
                $votes_res = 1;
146
                $rating_res = $rating * 20;
147
                $this->rating_model->insert_rating($data);
148
            }
149
            //Change rating for product
150
            if ($type == 'product') {
151
                if (SProductsQuery::create()->findPk($id) !== null) {
152
                    $model = SProductsRatingQuery::create()->findPk($id);
153
                    if ($model === null) {
154
                        $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...
155
                        $model->setProductId($id);
156
                    }
157
                    $rating_res = (($model->getRating() + $rating) / ($model->getVotes() + 1)) * 20;
158
                    $votes_res = $model->getVotes() + 1;
159
160
                    $model->setVotes($model->getVotes() + 1);
161
                    $model->setRating($model->getRating() + $rating);
162
                    $model->save();
163
                }
164
            }
165
            //Save in session user's info
166
            $this->session->set_userdata('voted_g' . $id . $type, true);
167
168
            //If ajax request than return data for with new rating and votes
169
            if ($this->input->is_ajax_request()) {
170
                return json_encode(
171
                    [
172
                        'rate' => "$rating_res",
173
                        'votes' => "$votes_res"
174
                    ]
175
                );
176
            }
177
        } else {
178
            return json_encode(['rate' => null]);
179
        }
180
    }
181
182
    /**
183
     * Install module
184
     */
185 View Code Duplication
    public function _install() {
186
187
        $this->load->dbforge();
188
        ($this->dx_auth->is_admin()) OR exit;
189
        $fields = [
190
            'id' => [
191
                'type' => 'INT',
192
                'auto_increment' => TRUE
193
            ],
194
            'id_type' => [
195
                'type' => 'VARCHAR',
196
                'constraint' => '25',
197
                'null' => TRUE,
198
            ],
199
            'type' => [
200
                'type' => 'VARCHAR',
201
                'constraint' => '25',
202
                'null' => TRUE,
203
            ],
204
            'votes' => [
205
                'type' => 'INT',
206
            ],
207
            'rating' => [
208
                'type' => 'INT',
209
            ],
210
        ];
211
212
        $this->dbforge->add_field($fields);
213
        $this->dbforge->add_key('id', TRUE);
214
        $this->dbforge->create_table('rating');
215
216
        $this->db->where('name', 'star_rating');
217
        $this->db->update('components', ['enabled' => 1]);
218
    }
219
220
    /**
221
     * Deinstall module
222
     */
223
    public function _deinstall() {
224
225
        $this->load->dbforge();
226
        ($this->dx_auth->is_admin()) OR exit;
227
        $this->dbforge->drop_table('rating');
228
    }
229
230
}