Lib_seo   A
last analyzed

Complexity

Total Complexity 40

Size/Duplication

Total Lines 446
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 446
rs 9.2
c 0
b 0
f 0
wmc 40
lcom 2
cbo 0

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 3
A init() 0 10 2
A get_keywords() 0 14 2
A get_description() 0 21 2
B explode_str_on_words() 0 123 1
A count_words() 0 16 4
A renderGA() 0 30 4
C renderGAForCart() 0 59 11
A renderYaMetrica() 0 35 2
A renderYandexWebmaster() 0 9 2
A renderGoogleWebmaster() 0 9 2
A getCustomParams() 0 13 3
A setCustomParams() 0 6 2

How to fix   Complexity   

Complex Class

Complex classes like Lib_seo often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Lib_seo, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
if (!defined('BASEPATH')) {
4
    exit('No direct script access allowed');
5
}
6
7
/**
8
 * ImageCMS
9
 * Seo module
10
 * Create keywords and description
11
 */
12
class Lib_seo
13
{
14
15
    /**
16
     * @var bool
17
     */
18
    protected $orderJustMacked = FALSE;
19
20
    /**
21
     * @var array
22
     */
23
    public $origin_arr;
24
25
    /**
26
     * @var array
27
     */
28
    public $modif_arr;
29
30
    /**
31
     * @var int
32
     */
33
    public $min_word_length = 3;
34
35
    /**
36
     * @var int
37
     */
38
    public $desc_chars = 160;
39
40
    /**
41
     * GA custom params
42
     * @var array
43
     */
44
    private $custom = [];
45
46
    /**
47
     * Lib_seo constructor.
48
     */
49
    public function __construct() {
50
51
        if (CI::$APP->session->flashdata('makeOrderForGA') == true) {
52
            $this->orderJustMacked = TRUE;
53
        }
54
55
        CI::$APP->load->library('DX_Auth');
56
57
        if (CI::$APP->dx_auth->is_logged_in()) {
58
            $this->setCustomParams('userId', md5(CI::$APP->dx_auth->get_user_id()));
59
        }
60
    }
61
62
    /**
63
     * @param array $settings
64
     */
65
    public function init($settings) {
66
67
        $CI = &get_instance();
68
        if (!strstr($CI->uri->uri_string(), 'shop/order/view')) {
69
            $CI->template->registerJsScript($this->renderGA($settings));
0 ignored issues
show
Documentation introduced by
$settings is of type array, but the function expects a null|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...
70
        }
71
        $CI->template->registerJsScript($this->renderYaMetrica($settings), 'after');
0 ignored issues
show
Documentation introduced by
$settings is of type array, but the function expects a null|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...
72
        $CI->template->registerJsScript($this->renderYandexWebmaster($settings));
73
        $CI->template->registerJsScript($this->renderGoogleWebmaster($settings));
74
    }
75
76
    /**
77
     * Create keywords from text
78
     * @param string $text
79
     * @param bool $as_array
80
     * @return array|string
81
     */
82
    public function get_keywords($text, $as_array = FALSE) {
83
84
        $text = strip_tags($text);
85
        $text = mb_strtolower($text, 'utf-8');
86
        $this->explode_str_on_words($text);
87
        $this->count_words();
88
        $arr = array_slice($this->modif_arr, 0, 30);
89
90
        if ($as_array === FALSE) {
91
            return implode(', ', array_keys($arr));
92
        } else {
93
            return $arr;
94
        }
95
    }
96
97
    /**
98
     * @param string $text
99
     * @return string
100
     */
101
    public function get_description($text) {
102
103
        $delete = [
104
                   ';',
105
                   '"',
106
                   '&mdash',
107
                   '&nbsp;',
108
                  ];
109
110
        $tags = get_html_translation_table(HTML_ENTITIES);
111
112
        foreach ($tags as $v) {
113
            $text = str_replace($v, '', $text);
114
        }
115
116
        $text = str_replace($delete, '', $text);
117
        $text = str_replace("\n", ' ', $text);
118
        $text = str_replace("\r", ' ', $text);
119
120
        return trim(mb_substr(strip_tags(stripslashes($text)), 0, 255, 'utf-8'));
121
    }
122
123
    /**
124
     * Explode text on words
125
     * @param string $text
126
     * @return array
127
     */
128
    public function explode_str_on_words($text) {
129
130
        $search = [
131
                   "'ё'",
132
                   "'<script[^>]*?>.*?</script>'si",
133
                   "'<[\/\!]*?[^<>]*?>'si",
134
                   "'([\r\n])[\s]+'",
135
                   "'&(quot|#34);'i",
136
                   "'&(amp|#38);'i",
137
                   "'&(lt|#60);'i",
138
                   "'&(gt|#62);'i",
139
                   "'&(nbsp|#160);'i",
140
                   "'&(iexcl|#161);'i",
141
                   "'&(cent|#162);'i",
142
                   "'&(pound|#163);'i",
143
                   "'&(copy|#169);'i",
144
                   "'&#(\d+);'i",
145
                  ];
146
        $replace = [
147
                    'е',
148
                    ' ',
149
                    ' ',
150
                    '\\1 ',
151
                    '" ',
152
                    ' ',
153
                    ' ',
154
                    ' ',
155
                    ' ',
156
                    chr(161),
157
                    chr(162),
158
                    chr(163),
159
                    chr(169),
160
                    'chr(\\1)',
161
                   ];
162
163
        $text = preg_replace($search, $replace, $text);
164
        $del_symbols = [
165
                        ',',
166
                        '.',
167
                        ';',
168
                        ':',
169
                        '"',
170
                        '#',
171
                        '\$',
172
                        '%',
173
                        '^',
174
                        '!',
175
                        '@',
176
                        '`',
177
                        '~',
178
                        '*',
179
                        '-',
180
                        '=',
181
                        '+',
182
                        '\\',
183
                        '|',
184
                        '/',
185
                        '>',
186
                        '<',
187
                        '(',
188
                        ')',
189
                        '&',
190
                        '?',
191
                        '¹',
192
                        "\t",
193
                        "\r",
194
                        "\n",
195
                        '{',
196
                        '}',
197
                        '[',
198
                        ']',
199
                        "'",
200
                        '“',
201
                        '”',
202
                        '•',
203
                        ' как ',
204
                        ' для ',
205
                        ' что ',
206
                        ' или ',
207
                        ' это ',
208
                        ' этих ',
209
                        'всех ',
210
                        ' вас ',
211
                        ' они ',
212
                        ' оно ',
213
                        ' еще ',
214
                        ' когда ',
215
                        ' где ',
216
                        ' эта ',
217
                        ' лишь ',
218
                        ' уже ',
219
                        ' вам ',
220
                        ' нет ',
221
                        ' если ',
222
                        ' надо ',
223
                        ' все ',
224
                        ' так ',
225
                        ' его ',
226
                        ' чем ',
227
                        ' даже ',
228
                        ' мне ',
229
                        ' есть ',
230
                        ' раз ',
231
                        ' два ',
232
                        'raquo',
233
                        'laquo',
234
                        '0',
235
                        '1',
236
                        '2',
237
                        '3',
238
                        '4',
239
                        '5',
240
                        '6',
241
                        '7',
242
                        '8',
243
                        '9',
244
                        'mdash',
245
                       ];
246
        $text = str_replace($del_symbols, ' ', $text);
247
        $text = preg_replace('( +)', ' ', $text);
248
        $this->origin_arr = explode(' ', trim($text));
249
        return $this->origin_arr;
250
    }
251
252
    /**
253
     * Count words in text
254
     */
255
    public function count_words() {
256
257
        $tmp_arr = [];
258
        foreach ($this->origin_arr as $val) {
259
            if (strlen(utf8_decode($val)) >= $this->min_word_length) {
260
                $val = mb_strtolower($val, 'utf-8');
261
262
                if (array_key_exists($val, $tmp_arr)) {
263
                    $tmp_arr[$val]++;
264
                } else {
265
                    $tmp_arr[$val] = 1;
266
                }
267
            }
268
        }
269
        $this->modif_arr = $tmp_arr;
270
    }
271
272
    /**
273
     * @param null|string $GAid
274
     * @return string
275
     */
276
    public function renderGA($GAid = null) {
277
278
        /* Show Google Analytics code if some value inserted in admin panel */
279
        if ($GAid['google_analytics_id']) {
280
            if ($this->getCustomParams()) {
281
                $custom = ', ' . $this->getCustomParams();
282
            }
283
284
            if ($GAid['google_analytics_ee'] == 1) {
285
                $require = "ga('require', 'ec');";
286
            } else {
287
                $require = "ga('require', 'ecommerce', 'ecommerce.js');";
288
            }
289
            $ga = "<script>
290
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
291
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
292
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
293
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
294
295
  ga('create', '{$GAid['google_analytics_id']}', 'auto' $custom);
296
  ga('require', 'displayfeatures');
297
  ga('send', 'pageview');
298
  
299
  $require
300
301
</script>";
302
303
            return $ga;
304
        }
305
    }
306
307
    /**
308
     * @param null|SProducts $model
309
     * @param null|string $GAid
310
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
311
     */
312
    public function renderGAForCart($model = null, $GAid = null) {
313
314
        /* Show Google Analytics code if some value inserted in admin panel */
315
        if ($GAid['google_analytics_id']) {
316
            if ($this->getCustomParams()) {
317
                $custom = ', ' . $this->getCustomParams();
318
            }
319
            $require = $GAid['google_analytics_ee'] == '1' ? "ga('require', 'ec');" : "ga('require', 'ecommerce', 'ecommerce.js');";
320
321
            $ga = "<script>
322
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
323
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
324
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
325
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
326
327
  ga('create', '{$GAid['google_analytics_id']}', 'auto' $custom);
328
  ga('require', 'displayfeatures');
329
  ga('send', 'pageview');
330
  
331
  $require";
332
            /* @var $model SOrders */
333
            if ($model && $this->orderJustMacked && $GAid['google_analytics_ee'] !== '1') {
334
                if ($model->getSDeliveryMethods()) {
335
                    $affiliation = $model->getSDeliveryMethods()->getName();
336
                }
337
                $ga .= "
338
            ga('ecommerce:addTransaction', {
339
  'id': '" . $model->getId() . "',
340
  'affiliation': '" . $affiliation . "',
341
  'revenue': '" . $model->getTotalPrice() . "',
342
  'shipping': '',
343
  'tax': '',
344
});";
345
346
                foreach ($model->getSOrderProductss() as $item) {
347
                    /* @var $product SProducts */
348
                    $product = $item->getSProducts();
349
                    foreach ($product->getProductVariants() as $v) {
350
                        if ($v->getid() == $item->getVariantId()) {
351
                            $Variant = $v;
352
                            break;
353
                        }
354
                    }
355
                    $ga .= "ga('ecommerce:addItem', {
356
    'id': '" . $model->getId() . "',
357
    'name': '" . encode($product->getName()) . ' ' . encode($item->getVariantName()) . "',
358
    'sku': '" . encode($Variant->getNumber()) . "',
359
    'category': '" . encode($product->getMainCategory()->getName()) . "',
360
    'price': '" . $item->toCurrency() . "',
361
    'quantity': '" . $item->getQuantity() . "',
362
  });";
363
                }
364
                $ga .= "ga('ecommerce:send');";
365
            }
366
            $ga .= '</script>';
367
368
            return $ga;
369
        }
370
    }
371
372
    /**
373
     * @param null|string $YaMetricaId
374
     * @return string
375
     */
376
    public function renderYaMetrica($YaMetricaId = null) {
377
378
        $YandexMetrik = '';
379
        if ($YaMetricaId['yandex_metric']) {
380
            $YandexMetrik = '<!-- Yandex.Metrika counter -->
381
382
                    <script type="text/javascript">
383
                    (function (d, w, c) {
384
                        (w[c] = w[c] || []).push(function() {
385
                            try {
386
                                w.yaCounter' . $YaMetricaId['yandex_metric'] . ' = new Ya.Metrika({id:"' . $YaMetricaId['yandex_metric'] . '",
387
                                        webvisor:true,
388
                                        clickmap:true,
389
                                        trackLinks:true,
390
                                        accurateTrackBounce:true});
391
                            } catch(e) { }
392
                        });
393
394
                        var n = d.getElementsByTagName("script")[0],
395
                            s = d.createElement("script"),
396
                            f = function () { n.parentNode.insertBefore(s, n); };
397
                        s.type = "text/javascript";
398
                        s.async = true;
399
                        s.src = (d.location.protocol == "https:" ? "https:" : "http:") + "//mc.yandex.ru/metrika/watch.js";
400
401
                        if (w.opera == "[object Opera]") {
402
                            d.addEventListener("DOMContentLoaded", f, false);
403
                        } else { f(); }
404
                    })(document, window, "yandex_metrika_callbacks");
405
                    </script>
406
                    <noscript><div><img src="//mc.yandex.ru/watch/' . $YaMetricaId['yandex_metric'] . '" style="position:absolute; left:-9999px;" alt="" /></div></noscript>
407
        <!-- /Yandex.Metrika counter -->';
408
        }
409
        return $YandexMetrik;
410
    }
411
412
    public function renderYandexWebmaster($YaWebmasterId = null) {
413
414
        $YaWebmaster = '';
415
        if ($YaWebmasterId['yandex_webmaster']) {
416
            $YaWebmaster = '<meta name=\'yandex-verification\' content=\'' . $YaWebmasterId['yandex_webmaster'] . '\' />';
417
        }
418
419
        return $YaWebmaster;
420
    }
421
422
    public function renderGoogleWebmaster($GWebmasterId = null) {
423
424
        $GWebmaster = '';
425
        if ($GWebmasterId['google_webmaster']) {
426
            $GWebmaster = '<meta name="google-site-verification" content="' . $GWebmasterId['google_webmaster'] . '" />';
427
        }
428
429
        return $GWebmaster;
430
    }
431
432
    public function getCustomParams($type = 'json') {
433
434
        if (empty($this->custom)) {
435
            return;
436
        }
437
        switch ($type) {
438
            case 'json':
439
                return json_encode($this->custom);
440
441
            default:
442
                return $this->custom;
443
        }
444
    }
445
446
    /**
447
     * @param string $name
448
     * @param string $val
449
     */
450
    public function setCustomParams($name, $val) {
451
452
        if ($name != '') {
453
            $this->custom[$name] = $val;
454
        }
455
    }
456
457
}
458
459
/* End of file lib_seo.php */