Completed
Branch BUG-9140-has-billing-form-igno... (f963e1)
by
unknown
853:47 queued 830:05
created

EEH_Export   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 146
Duplicated Lines 28.77 %

Coupling/Cohesion

Components 0
Dependencies 7
Metric Value
wmc 22
lcom 0
cbo 7
dl 42
loc 146
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A get_column_name_for_field() 0 3 1
C write_data_array_to_csv() 3 30 8
C get_csv_row() 24 24 7
A prepare_value_from_db_for_display() 15 15 4
A get_date_format_for_export() 0 3 1
A get_time_format_for_export() 0 3 1

How to fix   Duplicated Code   

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:

1
<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) exit('No direct script access allowed');
2
/**
3
 * Event Espresso
4
 *
5
 * Event Registration and Management Plugin for WordPress
6
 *
7
 * @ package			Event Espresso
8
 * @ author			Seth Shoultes
9
 * @ copyright		(c) 2008-2011 Event Espresso  All Rights Reserved.
10
 * @ license			http://eventespresso.com/support/terms-conditions/   * see Plugin Licensing *
11
 * @ link					http://www.eventespresso.com
12
 * @ version		 	4.0
13
 *
14
 * ------------------------------------------------------------------------
15
 *
16
 * EEH_Export Helper
17
 *
18
 * Static class for helping in creating exports
19
 *
20
 * @package			Event Espresso
21
 * @subpackage	/helpers/
22
 * @author				Brent Christensen
23
 *
24
 * ------------------------------------------------------------------------
25
 */
26
27
class EEH_Export {
28
	/**
29
	 * Gets the 'normal' column named for fields
30
	 * @param EE_Model_Field_Base $field
31
	 * @return string
32
	 */
33
	public static function get_column_name_for_field(EE_Model_Field_Base $field){
34
		return $field->get_nicename()."[".$field->get_name()."]";
35
	}
36
37
	/**
38
	 * Writes $data to the csv file open in $filehandle. uses the array indices of $data for column headers
39
	 *
40
	 * @param string 	$filepath
41
	 * @param array 	$data 2D array, 		first numerically-indexed,
42
	 *                    						and next-level-down preferably indexed by string
43
	 * @param boolean 	$write_column_headers 	whether or not we should add the keys in the bottom-most array
44
	 * 											as a row for headers in the CSV.
45
	 *                                            Eg, if $data looked like:
46
	 *                                            array(
47
	 *                                              	0=>array('EVT_ID'=>1,'EVT_name'=>'monkey'...),
48
	 * 													1=>array(...,...)
49
	 *                                            )
50
	 *
51
	 * @return boolean 		if we successfully wrote to the CSV or not. If there's no $data,
52
	 * 						we consider that a success (because we wrote everything there was...nothing)
53
	 * @throws EE_Error
54
	 */
55
	public static function write_data_array_to_csv( $filepath, $data, $write_column_headers = true ){
56
		EE_Registry::instance()->load_helper('Array');
57
58
		$new_file_contents = '';
59
		//determine if $data is actually a 2d array
60
		if ( $data && is_array($data) && is_array(EEH_Array::get_one_item_from_array($data))){
0 ignored issues
show
Bug Best Practice introduced by
The expression $data of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
61
			//make sure top level is numerically indexed,
62
63 View Code Duplication
			if( EEH_Array::is_associative_array($data)){
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
64
				throw new EE_Error(sprintf(__("top-level array must be numerically indexed. Does these look like numbers to you? %s","event_espresso"),implode(",",array_keys($data))));
65
			}
66
			$item_in_top_level_array = EEH_Array::get_one_item_from_array($data);
67
			//now, is the last item in the top-level array of $data an associative or numeric array?
68
			if( $write_column_headers &&
69
					EEH_Array::is_associative_array($item_in_top_level_array)){
70
				//its associative, so we want to output its keys as column headers
71
				$keys = array_keys($item_in_top_level_array);
72
				$new_file_contents .=  EEH_Export::get_csv_row( $keys );
73
74
			}
75
			//start writing data
76
			foreach($data as $data_row){
77
				$new_file_contents .= EEH_Export::get_csv_row( $data_row);
78
			}
79
			return EEH_File::write_to_file( $filepath, EEH_File::get_file_contents( $filepath ) . $new_file_contents );
80
		}else{
81
			//no data TO write... so we can assume that's a success
82
			return true;
83
		}
84
	}
85
86
87
88
	 /**
89
	  *
90
	 *	Writes a row to the csv file
91
	 *	@param array $row - individual row of csv data
92
	 *	@param string $delimiter - csv delimiter
93
	 *	@param string $enclosure - csv enclosure
94
	 *	@param bool $mysql_null - allows php NULL to be overridden with MySQl's insertable NULL value
95
	 *	@return string of text for teh csv file
96
	 */
97 View Code Duplication
	public static function get_csv_row ( array $row, $delimiter = ',', $enclosure = '"', $mysql_null = false ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
98
		//Allow user to filter the csv delimiter and enclosure for other countries csv standards
99
		$delimiter = apply_filters( 'FHEE__EE_CSV__fputcsv2__delimiter', $delimiter );
100
		$enclosure = apply_filters( 'FHEE__EE_CSV__fputcsv2__enclosure', $enclosure );
101
102
		$delimiter_esc = preg_quote($delimiter, '/');
103
		$enclosure_esc = preg_quote($enclosure, '/');
104
105
		$output = array();
106
		foreach ($row as $field_value) {
107
			if(is_object($field_value) || is_array($field_value)){
108
				$field_value = serialize($field_value);
109
			}
110
			if ($field_value === null && $mysql_null ) {
111
				$output[] = 'NULL';
112
				continue;
113
			}
114
115
			$output[] = preg_match("/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field_value) ?
116
				( $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field_value) . $enclosure ) : $field_value;
117
		}
118
119
		return  implode($delimiter, $output) . PHP_EOL;
120
	}
121
122
123
124
	/**
125
	 * Shortcut for preparing a database result for display
126
	 * @param EEM_Base $model
127
	 * @param string $field_name
128
	 * @param string $raw_db_value
129
	 * @param boolean|string $pretty_schema true to display pretty, a string to use a specific "Schema", or false to NOT display pretty
130
	 * @return string
131
	 */
132 View Code Duplication
	public static function prepare_value_from_db_for_display( $model, $field_name,  $raw_db_value, $pretty_schema = true ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
133
		$field_obj = $model->field_settings_for( $field_name );
134
		$value_on_model_obj = $field_obj->prepare_for_set_from_db( $raw_db_value );
135
		if( $field_obj instanceof EE_Datetime_Field ) {
136
			$field_obj->set_date_format( EEH_Export::get_date_format_for_export( $field_obj->get_date_format( $pretty_schema ) ), $pretty_schema );
0 ignored issues
show
Bug introduced by
It seems like $pretty_schema defined by parameter $pretty_schema on line 132 can also be of type string; however, EE_Datetime_Field::get_date_format() does only seem to accept boolean, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
Bug introduced by
It seems like $pretty_schema defined by parameter $pretty_schema on line 132 can also be of type string; however, EE_Datetime_Field::set_date_format() does only seem to accept boolean, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
137
			$field_obj->set_time_format( EEH_Export::get_time_format_for_export( $field_obj->get_time_format( $pretty_schema ) ), $pretty_schema );
0 ignored issues
show
Bug introduced by
It seems like $pretty_schema defined by parameter $pretty_schema on line 132 can also be of type string; however, EE_Datetime_Field::get_time_format() does only seem to accept boolean, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
Bug introduced by
It seems like $pretty_schema defined by parameter $pretty_schema on line 132 can also be of type string; however, EE_Datetime_Field::set_time_format() does only seem to accept boolean, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
138
		}
139
		if( $pretty_schema === true){
140
			return $field_obj->prepare_for_pretty_echoing( $value_on_model_obj );
141
		}elseif( is_string( $pretty_schema ) ) {
142
			return $field_obj->prepare_for_pretty_echoing($value_on_model_obj, $pretty_schema );
0 ignored issues
show
Unused Code introduced by
The call to EE_Model_Field_Base::prepare_for_pretty_echoing() has too many arguments starting with $pretty_schema.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
143
		}else{
144
			return $field_obj->prepare_for_get( $value_on_model_obj );
145
		}
146
	}
147
148
149
150
	/**
151
	 * Gets the date format to use in exports. filterable
152
	 * @param string $current_format
153
	 * @return string
154
	 */
155
	public static function get_date_format_for_export( $current_format = null ) {
156
		return apply_filters( 'FHEE__EE_CSV__get_date_format_for_csv__format', 'Y-m-d', $current_format );
157
	}
158
159
160
161
	/**
162
	 * Gets the time format we want to use in exports. Filterable
163
	 * @param string $current_format
164
	 * @return string
165
	 */
166
	public static function get_time_format_for_export( $current_format = null ) {
167
		return apply_filters( 'FHEE__EE_CSV__get_time_format_for_csv__format', 'H:i:s', $current_format );
168
	}
169
170
171
172
}
173