Package   F
last analyzed

Complexity

Total Complexity 81

Size/Duplication

Total Lines 518
Duplicated Lines 39 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
dl 202
loc 518
rs 1.5789
c 0
b 0
f 0
wmc 81
lcom 0
cbo 1

29 Methods

Rating   Name   Duplication   Size   Complexity  
A Package() 14 14 2
A package_list() 10 10 1
A package_list_json() 0 12 1
A package_list_reseller() 10 10 1
A package_list_search() 14 14 3
A package_list_clearsearchfilter() 0 4 1
A package_add() 0 5 1
A package_edit() 0 14 3
B package_save() 0 38 5
A package_delete() 0 17 2
A package_delete_multiple() 0 6 1
A package_pattern_list() 0 11 2
A package_pattern_list_json() 19 19 4
A package_counter() 7 7 1
A package_counter_json() 0 12 1
A package_counter_report_export() 0 19 3
A package_pattern_json() 14 14 1
A package_patterns_add() 9 9 1
A package_patterns_add_json() 0 13 1
A package_patterns_add_info() 0 6 1
A package_patterns_delete() 0 4 1
A package_patterns_selected_delete() 0 6 1
A package_quick_search() 7 7 2
A package_patterns_import() 13 13 3
A package_patterns_download_sample_file() 12 12 1
C package_patterns_preview_file() 30 60 13
D package_patterns_import_file() 25 85 15
C data_validate() 10 31 8
A package_patterns_error_download() 8 8 1

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Package 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 Package, and based on these observations, apply Extract Interface, too.

1
<?php
2
###############################################################################
3
# ASTPP - Open Source VoIP Billing Solution
4
#
5
# Copyright (C) 2016 iNextrix Technologies Pvt. Ltd.
6
# Samir Doshi <[email protected]>
7
# ASTPP Version 3.0 and above
8
# License https://www.gnu.org/licenses/agpl-3.0.html
9
#
10
# This program is free software: you can redistribute it and/or modify
11
# it under the terms of the GNU Affero General Public License as
12
# published by the Free Software Foundation, either version 3 of the
13
# License, or (at your option) any later version.
14
# 
15
# This program is distributed in the hope that it will be useful,
16
# but WITHOUT ANY WARRANTY; without even the implied warranty of
17
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
# GNU Affero General Public License for more details.
19
# 
20
# You should have received a copy of the GNU Affero General Public License
21
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
22
###############################################################################
23
24
class Package extends MX_Controller {
25
26 View Code Duplication
	function Package() {
27
		parent::__construct();
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (__construct() instead of Package()). Are you sure this is correct? If so, you might want to change this to $this->__construct().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
28
29
		$this->load->helper('template_inheritance');
30
31
		$this->load->library('session');
32
		$this->load->library('package_form');
33
		$this->load->library('astpp/form');
34
		$this->load->model('package_model');
35
		$this->load->library('csvreader');
36
37
		if ($this->session->userdata('user_login') == FALSE)
38
			redirect(base_url() . '/astpp/login');
39
	}
40
41
   
42 View Code Duplication
	function package_list() {
43
		$data['username'] = $this->session->userdata('user_name');
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
44
		$data['page_title'] = 'Packages';
45
$data['search_flag'] = true;
46
		$this->session->set_userdata('advance_search', 0);
47
		$data['grid_fields'] = $this->package_form->build_package_list_for_admin();
48
		$data["grid_buttons"] = $this->package_form->build_grid_buttons();
49
		$data['form_search'] = $this->form->build_serach_form($this->package_form->get_package_search_form());
50
		$this->load->view('view_package_list', $data);
51
	}
52
53
	/**
54
	 * -------Here we write code for controller accounts functions account_list------
55
	 * Listing of Accounts table data through php function json_encode
56
	 */
57
	function package_list_json() {
58
		$json_data = array();
59
		$count_all = $this->package_model->getpackage_list(false);
60
		$paging_data = $this->form->load_grid_config($count_all, $_GET['rp'], $_GET['page']);
61
		$json_data = $paging_data["json_paging"];
62
63
		$query = $this->package_model->getpackage_list(true, $paging_data["paging"]["start"], $paging_data["paging"]["page_no"]);
64
		$grid_fields = json_decode($this->package_form->build_package_list_for_admin());
65
		$json_data['rows'] = $this->form->build_grid($query, $grid_fields);
66
67
		echo json_encode($json_data);
68
	}
69 View Code Duplication
	function package_list_reseller($accountid,$accounttype){
70
	$json_data = array();
71
		$count_all = $this->package_model->get_reseller_package_list(false,$accountid,$accounttype);
72
		$paging_data = $this->form->load_grid_config($count_all, $_GET['rp'], $_GET['page']);
73
		$json_data = $paging_data["json_paging"];
74
		$query = $this->package_model->get_reseller_package_list(true,$accountid,$accounttype,$paging_data["paging"]["start"], $paging_data["paging"]["page_no"]);
75
		$grid_fields = json_decode($this->package_form->build_package_list_for_reseller());
76
		$json_data['rows'] = $this->form->build_grid($query, $grid_fields);
77
		echo json_encode($json_data);
78
	}
79 View Code Duplication
   function package_list_search() {
80
		$ajax_search = $this->input->post('ajax_search', 0);
81
82
		if ($this->input->post('advance_search', TRUE) == 1) {
83
			$this->session->set_userdata('advance_search', $this->input->post('advance_search'));
84
			$action = $this->input->post();
85
			unset($action['action']);
86
			unset($action['advance_search']);
87
			$this->session->set_userdata('package_list_search', $action);
88
		}
89
		if (@$ajax_search != 1) {
90
			redirect(base_url() . 'package/package_list/');
91
		}
92
	}
93
    
94
	function package_list_clearsearchfilter() {
95
		$this->session->set_userdata('advance_search', 0);
96
		$this->session->set_userdata('package_list_search', "");
97
	}
98
    
99
	 function package_add($type = "") {
0 ignored issues
show
Unused Code introduced by
The parameter $type is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
100
		$data['page_title'] = 'Create Package';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
101
		$data['form'] = $this->form->build_form($this->package_form->get_package_form_fields(), '');
102
		$this->load->view('view_package_add', $data);
103
	}
104
105
	function package_edit($edit_id = '') {
106
		$data['page_title'] = 'Package Details';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
107
		$accountinfo = $this->session->userdata("accountinfo");
108
		$reseller_id=$accountinfo['type'] == 1 ? $accountinfo['id']:0;
109
		$package_result = $this->db_model->getSelect("*", " packages", array('id' => $edit_id,"reseller_id"=>$reseller_id));
110
		if ($package_result->num_rows > 0) {
111
			$package_info=(array)$package_result->first_row();
112
			$data['form'] = $this->form->build_form($this->package_form->get_package_form_fields($package_info['id']), $package_info);
113
			$data['edit_id']=$package_info['id'];
114
			$this->load->view('view_packages_edit', $data);
115
		} else {
116
			redirect(base_url() . 'package/package_list/');
117
		}
118
	}
119
120
	function package_save($id="") {
0 ignored issues
show
Unused Code introduced by
The parameter $id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
121
		$add_array = $this->input->post();
122
		$data['form'] = $this->form->build_form($this->package_form->get_package_form_fields($add_array['id']), $add_array);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
123
		if ($add_array['id'] != '') {
124
			if ($this->form_validation->run() == FALSE) {
125
				$data['edit_id']= $add_array['id'];
126
				$data['validation_errors'] = validation_errors();
127
				$this->load->view('view_packages_edit', $data);
128
			} else {
129
				$this->package_model->edit_package($add_array, $add_array['id']);
130
				$this->session->set_flashdata('astpp_errormsg', 'Package updated successfully!');
131
				redirect(base_url() . 'package/package_list/');
132
				exit;
133
			}
134
		} else {
135
			$data['page_title'] = 'Create Package';
136
			if ($this->form_validation->run() == FALSE) {
137
				$data['validation_errors'] = validation_errors();
138
				$this->load->view('view_package_add', $data);
139
			} else {
140
141
				$this->package_model->add_package($add_array);
142
/**
143
ASTPP  3.0 
144
For Email Broadcast when package is add
145
**/
146
		$accountinfo = $this->db_model->getSelect("*", "accounts", array("pricelist_id" => $add_array['pricelist_id'],"status"=>0, "deleted"=>0));
147
		$accountinfo = $accountinfo->result_array();
148
				$this->session->set_flashdata('astpp_errormsg', 'Package added successfully!');
149
		foreach($accountinfo as $key => $value){
150
			$this->common->mail_to_users('add_package', $value);
151
		}
152
/**************************************/
153
				redirect(base_url() . 'package/package_list/');
154
				exit;
155
			}
156
		}
157
	}
158
159
    
160
161
	function package_delete($id) {
162
/**
163
ASTPP  3.0 
164
For Email Broadcast when package is add
165
**/	
166
	$package_detail = $this->db_model->getSelect("*", "packages", array("id"=>$id));
167
	$package_detail = $package_detail->result_array();
168
	$package_detail = $package_detail[0];
169
	$accountinfo = $this->db_model->getSelect("*", "accounts", array("pricelist_id" => $package_detail['pricelist_id'],"status"=>0, "deleted"=>0)); 
170
		$this->package_model->remove_package($id);
171
		$this->session->set_flashdata('astpp_notification', 'Package removed successfully!');
172
	foreach($accountinfo->result_array() as $key => $value){
173
		$this->common->mail_to_users('remove_package', $value);
174
	}	
175
/******************************************/
176
		redirect(base_url() . 'package/package_list/');
177
	}
178
    
179
	function package_delete_multiple() {
180
		$ids = $this->input->post("selected_ids", true);
181
		$where = "id IN ($ids)";
182
		$this->db->where($where);
183
		echo $this->db->delete("packages");
184
	}
185
186
	function package_pattern_list($package_id){
187
		$data['page_title'] = 'Package Codes';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
188
		if(!empty($package_id)){
189
			$data['grid_fields'] = $this->package_form->build_pattern_list_for_customer($package_id);
190
			$data['grid_buttons'] = $this->package_form->set_pattern_grid_buttons($package_id);
191
			$data["edit_id"] = $package_id;
192
			$this->load->view("view_package_pattern_list",$data);
193
		}else{
194
			redirect(base_url()."package/package_list/");
195
		}    
196
	}
197 View Code Duplication
	function package_pattern_list_json($package_id){
198
		$json_data = array();
199
		$instant_search=$this->session->userdata('left_panel_search_package_pattern');
200
		$like_str=!empty($instant_search) ? "(patterns like '%$instant_search%'  OR destination like '%$instant_search%' )" :null;
201
		if(!empty($like_str))
202
		$this->db->where($like_str);
203
		$where = array('package_id' => $package_id);
204
		$count_all = $this->db_model->countQuery("*", "package_patterns", $where);
205
		$paging_data = $this->form->load_grid_config($count_all, $_GET['rp'], $_GET['page']);
206
		$json_data = $paging_data["json_paging"];
207
		if(!empty($like_str))
208
		$this->db->where($like_str);
209
		$pattern_data = $this->db_model->select("*", "package_patterns", $where, "id", "ASC", $paging_data["paging"]["page_no"], $paging_data["paging"]["start"]);
210
        
211
		$grid_fields = json_decode($this->package_form->build_pattern_list_for_customer($package_id));
212
		$json_data['rows'] = $this->form->build_grid($pattern_data, $grid_fields);
213
214
		echo json_encode($json_data);
215
	}
216 View Code Duplication
	function package_counter() {
217
		$data['username'] = $this->session->userdata('user_name');
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
218
		$data['page_title'] = 'Usage Report';
219
		$data['grid_fields'] = $this->package_form->build_package_counter_list_for_admin();
220
	$data["grid_buttons"] = $this->package_form->build_package_counter_report();
221
		$this->load->view('view_package_counter_report', $data);
222
	}
223
224
	/**
225
	 * -------Here we write code for controller accounts functions account_list------
226
	 * Listing of Accounts table data through php function json_encode
227
	 */
228
	function package_counter_json() {
229
		$json_data = array();
230
		$count_all = $this->package_model->getpackage_counter_list(false);
231
		$paging_data = $this->form->load_grid_config($count_all, $_GET['rp'], $_GET['page']);
232
		$json_data = $paging_data["json_paging"];
233
234
		$query = $this->package_model->getpackage_counter_list(true, $paging_data["paging"]["start"], $paging_data["paging"]["page_no"]);
235
		$grid_fields = json_decode($this->package_form->build_package_counter_list_for_admin());
236
		$json_data['rows'] = $this->form->build_grid($query, $grid_fields);
237
238
		echo json_encode($json_data);
239
	}
240
	function package_counter_report_export(){
241
		$query = $this->db_model->getSelect("*", "counters", '');
242
		$outbound_array = array();
243
		ob_clean();
244
		$outbound_array[] = array("Package Name", "Account",  "Used Seconds");
245
		if ($query->num_rows() > 0) {
246
247
			foreach ($query->result_array() as $row) {
248
			 $outbound_array[] = array(
249
						$this->common->get_field_name('package_name', 'packages', $row['package_id']),
250
						$this->common->get_field_name_coma_new('first_name,last_name,number', 'accounts', $row['accountid']),
251
						$row['seconds']
252
						);
253
				}
254
			}
255
		$this->load->helper('csv');
256
		array_to_csv($outbound_array, 'Usage_Report_' . date("Y-m-d") . '.csv');
257
    
258
	}
259 View Code Duplication
	function package_pattern_json($package_id){
260
		$json_data = array();
261
		$where = array('package_id' => $package_id);
262
263
		$count_all = $this->db_model->countQuery("*", "package_patterns", $where);
264
		$paging_data = $this->form->load_grid_config($count_all, $_GET['rp'], $_GET['page']);
265
		$json_data = $paging_data["json_paging"];
266
267
		$pattern_data = $this->db_model->select("*", "package_patterns", $where, "id", "ASC", $paging_data["paging"]["page_no"], $paging_data["paging"]["start"]);
268
		$grid_fields = json_decode($this->package_form->build_pattern_list_for_customer($package_id));
269
		$json_data['rows'] = $this->form->build_grid($pattern_data, $grid_fields);
270
271
		echo json_encode($json_data);
272
	}
273
    
274 View Code Duplication
	function package_patterns_add($packageid) {
275
		$data['username'] = $this->session->userdata('user_name');
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
276
		$data['page_title'] = 'Unblocked Prefixes';
277
		$this->session->set_userdata('advance_search', 0);
278
		$this->load->module('rates/rates');
279
		$data['patters_grid_fields'] = $this->rates->rates_form->build_block_pattern_list_for_customer();
280
		$data["packageid"] = $packageid;
281
		$this->load->view('view_prefix_list', $data);
282
	}
283
	function package_patterns_add_json($accountid) {
284
		$this->load->module('rates/rates');
285
		$json_data = array();
286
		$count_all = $this->rates_model->getunblocked_package_pattern($accountid,false);
287
		$paging_data = $this->form->load_grid_config($count_all, $_GET['rp'], $_GET['page']);
288
		$json_data = $paging_data["json_paging"];
289
290
		$query = $this->rates->rates_model->getunblocked_package_pattern($accountid,true, $paging_data["paging"]["start"], $paging_data["paging"]["page_no"]);
291
		$grid_fields = json_decode($this->rates->rates_form->build_block_pattern_list_for_customer());
292
		$json_data['rows'] = $this->rates->form->build_grid($query, $grid_fields);
293
294
		echo json_encode($json_data);
295
	}
296
	function package_patterns_add_info($packageid) {	
297
		$result = $this->package_model->insert_package_pattern($this->input->post('prefixies', true),$packageid);
298
		unset($_POST);
299
		echo $result;
300
		exit;
301
	}
302
	function package_patterns_delete($packageid, $patternid) {
303
		$this->db->delete("package_patterns", array("id" => $patternid));
304
		redirect(base_url() . "package/package_pattern_list/$packageid");
305
	}
306
	function package_patterns_selected_delete(){
307
		$ids = $this->input->post("selected_ids", true);
308
		$where = "id IN ($ids)";
309
		unset($_POST);
310
		echo $this->db->delete("package_patterns",$where);
311
	}
312
    
313 View Code Duplication
	function package_quick_search($module_name){
0 ignored issues
show
Unused Code introduced by
The parameter $module_name is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
314
		$action = $this->input->post();
315
		$this->session->set_userdata('left_panel_search_package_pattern',"");
316
		if(!empty($action['left_panel_search'])){
317
			$this->session->set_userdata('left_panel_search_package_pattern', $action['left_panel_search']);
318
		}
319
	}
320
321
322 View Code Duplication
	function package_patterns_import($edit_id) {
323
		//echo "nick";exit;
0 ignored issues
show
Unused Code Comprehensibility introduced by
84% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
324
		$data['page_title'] = 'Import Package Patterns';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
325
		$this->session->set_userdata('import_package_code_csv',"");
326
		$error_data =  $this->session->userdata('import_package_code_csv_error');
327
		$full_path = $this->config->item('rates-file-path');
328
		if(file_exists($full_path.$error_data) && $error_data != ""){
329
			unlink($full_path.$error_data);
330
			$this->session->set_userdata('import_package_code_csv_error',"");
331
		}
332
		$data['edit_id'] = $edit_id;
333
		$this->load->view('view_import_package_code', $data);
334
	}
335
    
336
    
337 View Code Duplication
	function package_patterns_download_sample_file($file_name){
338
		$this->load->helper('download');
339
		$full_path = base_url()."assets/Rates_File/".$file_name.".csv";
340
		$arrContextOptions=array(
341
			"ssl"=>array(
342
			"verify_peer"=>false,
343
			"verify_peer_name"=>false,
344
			),
345
		);  
346
		$file = file_get_contents($full_path, false, stream_context_create($arrContextOptions));
347
		force_download("samplefile.csv", $file); 
348
	}
349
    
350
    
351
	function package_patterns_preview_file($edit_id){
352
	$invalid_flag= false;
353
	$data=array();
354
	$data['page_title'] = 'Import Package Patterns';
355
	$check_header=$this->input->post('check_header',true);
356
	if(empty($_FILES) || !isset($_FILES)){
357
	  redirect(base_url()."package/package_pattern_list/");
358
	}
359
	$get_extension=strpos($_FILES['package_code_import']['name'],'.');
360
	$new_final_arr_key = $this->config->item('package-code-field');
361
	if(!$get_extension){
362
		$data['error']= "Please Upload File Atleast";
363
		}
364
		//echo "<pre>";print_r($_FILES);exit;
0 ignored issues
show
Unused Code Comprehensibility introduced by
82% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
365
		if (isset($_FILES['package_code_import']['name']) && $_FILES['package_code_import']['name'] != "" ) {
366
			list($txt,$ext) = explode(".", $_FILES['package_code_import']['name']);
0 ignored issues
show
Unused Code introduced by
The assignment to $txt is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
367
            
368 View Code Duplication
			if($ext == "csv" && $_FILES['package_code_import']['size'] > 0){ 
369
				$error = $_FILES['package_code_import']['error'];
370
				if ($error == 0) {
371
					$uploadedFile = $_FILES["package_code_import"]["tmp_name"];
372
					$csv_data=$this->csvreader->parse_file($uploadedFile,$new_final_arr_key,$check_header);
373
					if(!empty($csv_data)){
374
			$full_path = $this->config->item('rates-file-path');
375
			//echo "<pre>";print_r($full_path);exit;
0 ignored issues
show
Unused Code Comprehensibility introduced by
82% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
376
					$actual_file_name = "ASTPP-ORIGIN-RATES-".date("Y-m-d H:i:s"). "." . $ext;
377
					//echo "<pre>";print_r($actual_file_name);exit;
0 ignored issues
show
Unused Code Comprehensibility introduced by
82% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
378
					if (move_uploaded_file($uploadedFile,$full_path.$actual_file_name)) {
379
			$flag=false;
380
			//$data['trunkid']=isset($_POST['trunk_id']) && $_POST['trunk_id'] > 0 ? $_POST['trunk_id'] : 0;
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
381
						$data['csv_tmp_data'] = $csv_data;
382
						//$data['pricelistid'] = $_POST['pricelist_id'];
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
383
						$data['page_title'] = "Package Patterns Preview";
384
						$data['check_header']=$check_header;
385
						$this->session->set_userdata('import_package_code_csv',$actual_file_name);
386
					}else{
387
						$data['error'] = "File Uploading Fail Please Try Again";
388
					}
389
				}
390
			 }   
391
			else{
392
					$data['error']=="File Uploading Fail Please Try Again";
393
				}
394
		   }
395
		   else {
396
				$data['error'] = "Invalid file format : Only CSV file allows to import records(Can't import empty file)";
397
			}
398
			}else{
399
		$invalid_flag=true;
400
			}
401
		if ($invalid_flag) {
402
			$str = '';
403
			if (empty($_FILES['package_code_import']['name'])) {
404
				$str.= '<br/>Please Select File.';
405
			}
406
			$data['error']=$str;
407
		}
408
		 $data['edit_id'] = $edit_id;
409
		$this->load->view('view_import_package_code', $data);
410
	}
411
    
412
    
413
	function package_patterns_import_file($edit_id,$check_header=false) {
414
		//echo $edit_id."===="; exit;
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
415
	   $new_final_arr = array();
416
		$invalid_array = array();
417
		$new_final_arr_key = $this->config->item('package-code-field');
418
	$screen_path = $this->config->item('screen_path');
419
	$reseller_id=0;
420
		if ($this->session->userdata('logintype') == 1 || $this->session->userdata('logintype') == 5) {
421
			$reseller_id = $this->session->userdata["accountinfo"]['id'];
422
		}
423
        
424
		$full_path = $this->config->item('rates-file-path');
425
		//echo "<pre>";print_r($full_path);exit;
0 ignored issues
show
Unused Code Comprehensibility introduced by
82% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
426
		$originationrate_file_name = $this->session->userdata('import_package_code_csv');	
427
		$csv_tmp_data = $this->csvreader->parse_file($full_path.$originationrate_file_name,$new_final_arr_key,$check_header); 
428
		//echo "<pre>";print_r($csv_tmp_data);exit;
0 ignored issues
show
Unused Code Comprehensibility introduced by
82% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
429
	$i=0; 
430
		 $pattern_arr=array();
431
		foreach ($csv_tmp_data as $key => $csv_data) {	
432
	  if(isset($csv_data['patterns']) && $csv_data['patterns']!= '' && $i != 0){
433
		$str=null;
434
		$pattern=$csv_data['patterns'];
435
		 if(!in_array($csv_data['patterns'],$pattern_arr)){
436
			$this->db->select('count(id) as count');
437
			$this->db->where('patterns',"^".$csv_data['patterns'].".*");
438
			$this->db->where('package_id',$edit_id);
439
			$pattern_res=(array)$this->db->get('package_patterns')->first_row();
440
			if($pattern_res['count'] ==0){
441
			$csv_data['destination']= isset($csv_data['destination'])? $csv_data['destination'] :'';
442
			$str=$this->data_validate($csv_data);
443
			if($str != ""){
444
			$invalid_array[$i]=$csv_data;
445
			$invalid_array[$i]['error'] = $str;
446
		}
447
		else{
448
		  $csv_data['patterns'] = "^" . $csv_data['patterns'] . ".*";
449
		  $csv_data['package_id'] = $edit_id;
450
		  $new_final_arr[$i]=$csv_data;
451
		  $pattern_arr[$csv_data['patterns']]=$csv_data['patterns'];
452
		}
453
		}else{
454
			$invalid_array[$i]=$csv_data;
455
			$invalid_array[$i]['error'] = "Duplicate pattern found from  database.";
456
		 }
457
	  }else{
458
		  $invalid_array[$i]=$csv_data;
459
		  $invalid_array[$i]['error'] = "Duplicate pattern found from import file";
460
		  }
461
		  $pattern_arr[$csv_data['patterns']]=$pattern;
462
	  }
463
464
		  $i++;
465
		}
466
		  if(!empty($new_final_arr)){
467
  		$result = $this->package_model->bulk_insert_package_pattern($new_final_arr);
468
		  }
469
	   //unlink($full_path.$originationrate_file_name);
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
470
	 $count=count($invalid_array);
471
	 //echo "<pre>";print_r($count);exit;
0 ignored issues
show
Unused Code Comprehensibility introduced by
82% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
472 View Code Duplication
		if($count >0){
473
			$session_id = "-1";
474
			$fp = fopen($full_path.$session_id.'.csv', 'w');
475
			foreach($new_final_arr_key as $key=>$value){
476
		  $custom_array[0][$key]=ucfirst($key);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$custom_array was never initialized. Although not strictly required by PHP, it is generally a good practice to add $custom_array = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
477
			}
478
			$custom_array[0]['error']= "Error";
0 ignored issues
show
Bug introduced by
The variable $custom_array 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...
479
			$invalid_array =array_merge($custom_array,$invalid_array);
480
			foreach($invalid_array as $err_data){
481
					fputcsv($fp,$err_data);
482
			}
483
			fclose($fp);
484
		   $this->session->set_userdata('import_package_code_csv_error', $session_id.".csv");
485
		   $data["error"] = $invalid_array;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
486
		   $data['packageid'] = $edit_id;
487
		   $data['impoted_count'] = count($new_final_arr);
488
		   $data['failure_count'] = count($invalid_array)-1;
489
		   $data['page_title'] = 'Package Patterns Import Error';
490
		   //print_r($data)	;exit;
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
491
		   $this->load->view('view_import_error',$data);
492
		 } else{
493
	   $this->session->set_flashdata('astpp_errormsg', 'Package patterns imported successfully!');
494
	   //echo base_url()."package/package_pattern_list/" . $edit_id . "/";exit;
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
495
		   redirect(base_url()."package/package_pattern_list/" . $edit_id . "/");
496
		   }
497
	}
498
    
499
	  function data_validate($csvdata){
500
		  $str=null;
501
	  $alpha_regex = "/^[a-z ,.'-]+$/i";
502
	  $alpha_numeric_regex = "/^[a-z0-9 ,.'-]+$/i";
503
	  $email_regex = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/"; 
504
	  $str.= $csvdata['patterns']!= '' ? null : 'Code,';
505
	  $str=rtrim($str,',');
506
	  if(!$str){
507
		  $str.= is_numeric($csvdata['patterns']) ? null : 'Code,';
508
509
			$str.= preg_match( $alpha_numeric_regex, $csvdata['destination'] ) ? null :'Destination,';
510
	      
511 View Code Duplication
		  if($str){
512
		$str=rtrim($str,',');
513
		$error_field=explode(',',$str);
514
		$count = count($error_field);
515
		$str.= $count > 1 ? ' are not valid' : ' is not Valid';
516
		return $str;
517
		  }
518
		  else{
519
		  return false;
520
		  }
521
	  }
522
	  else{
523
	  $str=rtrim($str,',');
524
		$error_field=explode(',',$str);
525
		$count = count($error_field);
526
		$str.= $count > 1 ? ' are required' : ' is Required';
527
	return $str;
528
	}
529
  }
530
    
531 View Code Duplication
	function package_patterns_error_download(){
532
		$this->load->helper('download');
533
		$error_data =  $this->session->userdata('import_package_code_csv_error');
534
		$full_path = $this->config->item('rates-file-path');
535
		$data = file_get_contents($full_path.$error_data);
536
		force_download("Package_Code_error.csv", $data); 
537
538
		}
539
540
541
}
542
543
?>
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...
544
 
545