mc360::process()   F
last analyzed

Complexity

Conditions 16
Paths 579

Size

Total Lines 121
Code Lines 82

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 16
eloc 82
nc 579
nop 0
dl 0
loc 121
rs 2.5225
c 0
b 0
f 0

How to fix   Long Method    Complexity   

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
use OSC\OM\Mail;
3
use OSC\OM\Registry;
4
5
class mc360 {
6
    var $system = "osc";
7
    var $version = "1.1";
8
9
    var $debug = false;
10
11
    var $apikey = '';
12
    var $key_valid = false;
13
    var $store_id = '';
14
15
    function __construct() {
16
        $this->apikey = MODULE_HEADER_TAGS_MAILCHIMP_360_API_KEY;
17
        $this->store_id = MODULE_HEADER_TAGS_MAILCHIMP_360_STORE_ID;
18
        $this->key_valid = ((MODULE_HEADER_TAGS_MAILCHIMP_360_KEY_VALID == 'true') ? true : false);
19
20
        if (tep_not_null(MODULE_HEADER_TAGS_MAILCHIMP_360_DEBUG_EMAIL)) {
21
          $this->debug = true;
22
        }
23
24
        $this->validate_cfg();
25
    }
26
27
    function complain($msg){
28
            echo '<div style="position:absolute;left:0;top:0;width:100%;font-size:24px;text-align:center;background:#CCCCCC;color:#660000">MC360 Module: '.$msg.'</div><br />';
29
    }
30
31
    function validate_cfg(){
32
        $OSCOM_Db = Registry::get('Db');
33
34
        $this->valid_cfg = false;
0 ignored issues
show
Bug introduced by
The property valid_cfg does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
35
        if (empty($this->apikey)){
36
            $this->complain('You have not entered your API key. Please read the installation instructions.');
37
            return;
38
        }
39
40
        if (!$this->key_valid){
41
            $GLOBALS["mc_api_key"] = $this->apikey;
42
            $api = new MCAPI('notused','notused');
43
            $res = $api->ping();
0 ignored issues
show
Unused Code introduced by
$res 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...
44
            if ($api->errorMessage!=''){
45
                $this->complain('Server said: "'.$api->errorMessage.'". Your API key is likely invalid. Please read the installation instructions.');
46
                return;
47
            } else {
48
                $this->key_valid = true;
49
                $OSCOM_Db->save('configuration', ['configuration_value' => 'true'], ['configuration_key' => 'MODULE_HEADER_TAGS_MAILCHIMP_360_KEY_VALID']);
50
51
                if (empty($this->store_id)){
52
                    $this->store_id = md5(uniqid(rand(), true));
53
                    $OSCOM_Db->save('configuration', ['configuration_value' => $this->store_id], ['configuration_key' => 'MODULE_HEADER_TAGS_MAILCHIMP_360_STORE_ID']);
54
                }
55
            }
56
        }
57
58
        if (empty($this->store_id)){
59
            $this->complain('Your Store ID has not been set. This is not good. Contact support.');
60
        } else {
61
            $this->valid_cfg = true;
62
        }
63
    }
64
    function set_cookies(){
65
        if (!$this->valid_cfg){
66
            return;
67
        }
68
        $thirty_days = time()+60*60*24*30;
69
        if (isset($_REQUEST['mc_cid'])){
70
            setcookie('mailchimp_campaign_id',trim($_REQUEST['mc_cid']), $thirty_days);
71
        }
72
        if (isset($_REQUEST['mc_eid'])){
73
            setcookie('mailchimp_email_id',trim($_REQUEST['mc_eid']), $thirty_days);
74
        }
75
        return;
76
    }
77
78
    function process() {
79
        if (!$this->valid_cfg){
80
            return;
81
        }
82
83
        global $order, $insert_id;
84
85
        $OSCOM_Db = Registry::get('Db');
86
87
        $orderId = $insert_id; // just to make it obvious.
88
89
        $debug_email = '';
90
91
        if ($this->debug){
92
            $debug_email .= '------------[New Order ' . $orderId . ']-----------------' . "\n" .
93
                            '$order =' . "\n" .
94
                            print_r($order, true) .
95
                            '$_COOKIE =' . "\n" .
96
                            print_r($_COOKIE, true);
97
        }
98
99
        if (!isset($_COOKIE['mailchimp_campaign_id']) || !isset($_COOKIE['mailchimp_email_id'])){
100
            return;
101
        }
102
103
        if ($this->debug){
104
            $debug_email .= date('Y-m-d H:i:s') . ' current ids:' . "\n" .
105
                            date('Y-m-d H:i:s') . ' eid =' . $_COOKIE['mailchimp_email_id'] . "\n" .
106
                            date('Y-m-d H:i:s') . ' cid =' . $_COOKIE['mailchimp_campaign_id'] . "\n";
107
        }
108
109
        $Qorder = $OSCOM_Db->get('orders', 'orders_id', ['customers_id' => $_SESSION['customer_id']], 'date_purchased desc', 1);
110
111
        $totals_array = array();
112
        $Qtotals = $OSCOM_Db->get('orders_total', ['value', 'class'], ['orders_id' => $Qorder->valueInt('orders_id')]);
113
        while ($Qtotals->fetch()) {
114
            $totals_array[$Qtotals->value('class')] = $Qtotals->value('value');
115
        }
116
117
        $products_array = array();
118
        $Qproducts = $OSCOM_Db->get('orders_products', ['products_id', 'products_model', 'products_name', 'products_tax', 'products_quantity', 'final_price'], ['orders_id' => $Qorder->valueInt('orders_id')]);
119
        while ($Qproducts->fetch()) {
120
            $products_array[] = array('id' => $Qproducts->valueInt('products_id'),
121
                                    'name' => $Qproducts->value('products_name'),
122
                                    'model' => $Qproducts->value('products_model'),
123
                                    'qty' => $Qproducts->value('products_quantity'),
124
                                    'final_price' => $Qproducts->value('final_price'),
125
                                    );
126
            $totals_array['ot_tax'] += $Qproducts->value('product_tax');
127
        }
128
129
        $mcorder = array(
130
                'id' => $Qorder->valueInt('orders_id'),
131
                'total'=>$totals_array['ot_total'],
132
                'shipping'=>$totals_array['ot_shipping'],
133
                'tax'  =>$totals_array['ot_tax'],
134
                'items'=>array(),
135
                'store_id'=>$this->store_id,
136
                'store_name' => $_SERVER['SERVER_NAME'],
137
                'campaign_id'=>$_COOKIE['mailchimp_campaign_id'],
138
                'email_id'=>$_COOKIE['mailchimp_email_id'],
139
                'plugin_id'=>1216
140
                );
141
142
        foreach($products_array as $product){
143
            $item = array();
144
            $item['line_num'] = $line;
0 ignored issues
show
Bug introduced by
The variable $line does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
145
            $item['product_id'] = $product['id'];
146
            $item['product_name'] = $product['name'];
147
            $item['sku'] = $product['model'];
148
            $item['qty'] = $product['qty'];
149
            $item['cost'] = $product['final_price'];
150
151
            //All this to get a silly category name from here
152
            $Qcat = $OSCOM_Db->get('products_to_categories', 'categories_id', ['products_id' => $product['id']], null, 1);
153
154
            $cat_id = $Qcat->valueInt('categories_id');
155
156
            $item['category_id'] = $cat_id;
157
            $cat_name == '';
0 ignored issues
show
Bug introduced by
The variable $cat_name does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
158
            $continue = true;
159
            while($continue){
160
            //now recurse up the categories tree...
161
                $Qcat = $OSCOM_Db->prepare('select c.categories_id, c.parent_id, cd.categories_name from :table_categories c inner join :table_categories_description cd on c.categories_id = cd.categories_id where c.categories_id = :categories_id');
162
                $Qcat->bindInt(':categories_id', $cat_id);
163
                $Qcat->execute();
164
165
                if ($cat_name == ''){
166
                    $cat_name = $Qcat->value('categories_name');
167
                } else {
168
                    $cat_name = $Qcat->value('categories_name') .' - '.$cat_name;
169
                }
170
                $cat_id = $Qcat->valueInt('parent_id');
171
                if ($cat_id==0){
172
                    $continue = false;
173
                }
174
            }
175
            $item['category_name'] = $cat_name;
176
177
            $mcorder['items'][] = $item;
178
        }
179
180
        $GLOBALS["mc_api_key"] = $this->apikey;
181
        $api = new MCAPI('notused','notused');
182
        $res = $api->campaignEcommAddOrder($mcorder);
0 ignored issues
show
Unused Code introduced by
$res 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...
183
        if ($api->errorMessage!=''){
184
            if ($this->debug) {
185
              $debug_email .= 'Error:' . "\n" .
186
                               $api->errorMessage . "\n";
187
            }
188
        } else {
189
            //nothing
190
        }
191
        // send!()
192
193
        if ($this->debug && !empty($debug_email)) {
194
            $debugEmail = new Mail(MODULE_HEADER_TAGS_MAILCHIMP_360_DEBUG_EMAIL, null, STORE_OWNER_EMAIL_ADDRESS, STORE_OWNER, 'MailChimp Debug E-Mail');
195
            $debugEmail->setBody($debug_email);
196
            $debugEmail->send();
197
        }
198
  }//update
199
}//mc360 class
200
201
?>
0 ignored issues
show
Best Practice introduced by
It is not recommended to use PHP's closing tag ?> in files other than templates.

Using a closing tag in PHP files that only contain PHP code is not recommended as you might accidentally add whitespace after the closing tag which would then be output by PHP. This can cause severe problems, for example headers cannot be sent anymore.

A simple precaution is to leave off the closing tag as it is not required, and it also has no negative effects whatsoever.

Loading history...
202