Completed
Push — develop ( e2ac27...b5f4d0 )
by Zack
04:24
created

GravityView_Field_FileUpload   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 248
Duplicated Lines 29.84 %

Coupling/Cohesion

Components 0
Dependencies 4
Metric Value
wmc 23
lcom 0
cbo 4
dl 74
loc 248
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A field_options() 18 18 2
F get_files_array() 56 206 21

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
2
/**
3
 * @package GravityView
4
 */
5
6
7
/**
8
 * Add custom options for date fields
9
 */
10
class GravityView_Field_FileUpload extends GravityView_Field {
11
12
	var $name = 'fileupload';
13
14
	var $_gf_field_class_name = 'GF_Field_FileUpload';
15
16
	var $group = 'advanced';
17
18 View Code Duplication
	function field_options( $field_options, $template_id, $field_id, $context, $input_type ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
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...
19
20
		unset( $field_options['search_filter'] );
21
22
		if( 'edit' === $context ) {
23
			return $field_options;
24
		}
25
26
		$add_options['link_to_file'] = array(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$add_options was never initialized. Although not strictly required by PHP, it is generally a good practice to add $add_options = 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...
27
			'type' => 'checkbox',
28
			'label' => __( 'Display as a Link:', 'gravityview' ),
29
			'desc' => __('Display the uploaded files as links, rather than embedded content.', 'gravityview'),
30
			'value' => false,
31
			'merge_tags' => false,
32
		);
33
34
		return $add_options + $field_options;
35
	}
36
37
	/**
38
	 * Return an array of files prepared for output.
39
	 *
40
	 * Processes files by file type and generates unique output for each. Returns array for each file, with the following keys:
41
	 * - `file_path` => The file path of the file, with a line break
42
	 * - `html` => The file output HTML formatted
43
	 *
44
	 * @since  1.2
45
	 * @todo  Support `playlist` shortcode for playlist of video/audio
46
	 * @param  string $value    Field value passed by Gravity Forms. String of file URL, or serialized string of file URL array
47
	 * @param  string $gv_class Field class to add to the output HTML
48
	 * @return array           Array of file output, with `file_path` and `html` keys (see comments above)
49
	 */
50
	static function get_files_array( $value, $gv_class ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
51
52
		$gravityview_view = GravityView_View::getInstance();
53
54
		extract( $gravityview_view->getCurrentField() );
0 ignored issues
show
Bug introduced by
$gravityview_view->getCurrentField() cannot be passed to extract() as the parameter $var_array expects a reference.
Loading history...
55
56
		$output_arr = array();
57
58
		// Get an array of file paths for the field.
59
		$file_paths = rgar( $field , 'multipleFiles' ) ? json_decode( $value ) : array( $value );
60
61
		// Process each file path
62
		foreach( $file_paths as $file_path ) {
63
64
			// If the site is HTTPS, use HTTPS
65
			if(function_exists('set_url_scheme')) { $file_path = set_url_scheme($file_path); }
66
67
			// This is from Gravity Forms's code
68
			$file_path = esc_attr(str_replace(" ", "%20", $file_path));
69
70
			// If the field is set to link to the single entry, link to it.
71
			$link = !empty( $field_settings['show_as_link'] ) ? GravityView_API::entry_link( $entry, $field ) : $file_path;
72
73
			// Get file path information
74
			$file_path_info = pathinfo($file_path);
75
76
			$html_format = NULL;
0 ignored issues
show
Unused Code introduced by
$html_format 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...
77
78
			$disable_lightbox = false;
79
80
			$disable_wrapped_link = false;
81
82
			// Is this an image?
83
			$image = new GravityView_Image(array(
84
				'src' => $file_path,
85
				'class' => 'gv-image gv-field-id-'.$field_settings['id'],
86
				'alt' => $field_settings['label'],
87
				'width' => (gravityview_get_context() === 'single' ? NULL : 250)
88
			));
89
90
			$content = $image->html();
91
92
			// The new default content is the image, if it exists. If not, use the file name as the content.
93
			$content = !empty( $content ) ? $content : $file_path_info['basename'];
94
95
			// If pathinfo() gave us the extension of the file, run the switch statement using that.
96
			$extension = empty( $file_path_info['extension'] ) ? NULL : strtolower( $file_path_info['extension'] );
97
98
99
			switch( true ) {
100
101
				// Audio file
102 View Code Duplication
				case in_array( $extension, wp_get_audio_extensions() ):
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...
103
104
					$disable_lightbox = true;
105
106
					if( shortcode_exists( 'audio' ) ) {
107
108
						$disable_wrapped_link = true;
109
110
						/**
111
						 * @filter `gravityview_audio_settings` Modify the settings passed to the `wp_video_shortcode()` function
112
						 * @since  1.2
113
						 * @param array $audio_settings Array with `src` and `class` keys
114
						 */
115
						$audio_settings = apply_filters( 'gravityview_audio_settings', array(
116
							'src' => $file_path,
117
							'class' => 'wp-audio-shortcode gv-audio gv-field-id-'.$field_settings['id']
118
						));
119
120
						/**
121
						 * Generate the audio shortcode
122
						 * @see http://codex.wordpress.org/Audio_Shortcode
123
						 * @see https://developer.wordpress.org/reference/functions/wp_audio_shortcode/
124
						 */
125
						$content = wp_audio_shortcode( $audio_settings );
126
127
					}
128
129
					break;
130
131
				// Video file
132 View Code Duplication
				case in_array( $extension, wp_get_video_extensions() ):
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...
133
134
					$disable_lightbox = true;
135
136
					if( shortcode_exists( 'video' ) ) {
137
138
						$disable_wrapped_link = true;
139
140
						/**
141
						 * @filter `gravityview_video_settings` Modify the settings passed to the `wp_video_shortcode()` function
142
						 * @since  1.2
143
						 * @param array $video_settings Array with `src` and `class` keys
144
						 */
145
						$video_settings = apply_filters( 'gravityview_video_settings', array(
146
							'src' => $file_path,
147
							'class' => 'wp-video-shortcode gv-video gv-field-id-'.$field_settings['id']
148
						));
149
150
						/**
151
						 * Generate the video shortcode
152
						 * @see http://codex.wordpress.org/Video_Shortcode
153
						 * @see https://developer.wordpress.org/reference/functions/wp_video_shortcode/
154
						 */
155
						$content = wp_video_shortcode( $video_settings );
156
157
					}
158
159
					break;
160
161
				// PDF
162
				case $extension === 'pdf':
163
164
					// PDF needs to be displayed in an IFRAME
165
					$link = add_query_arg( array( 'TB_iframe' => 'true' ), $link );
166
167
					break;
168
169
				// if not image, do not set the lightbox (@since 1.5.3)
170
				case !in_array( $extension, array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' ) ):
171
172
					$disable_lightbox = true;
173
174
					break;
175
176
			}
177
178
			// If using Link to File, override the content.
179
			// (We do this here so that the $disable_lightbox can be set. Yes, there's a little more processing time, but oh well.)
180
			if( !empty( $field_settings['link_to_file'] ) ) {
181
182
				// Force the content to be the file name
183
				$content =  $file_path_info["basename"];
184
185
				// Restore the wrapped link
186
				$disable_wrapped_link = false;
187
188
			}
189
190
			// Whether to use lightbox or not
191
			if( $disable_lightbox || empty( $gravityview_view->atts['lightbox'] ) || !empty( $field_settings['show_as_link'] ) ) {
0 ignored issues
show
Documentation introduced by
The property $atts is declared protected in GravityView_View. Since you implemented __get(), maybe consider adding a @property or @property-read annotation. This makes it easier for IDEs to provide auto-completion.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
192
193
				$link_atts = empty( $field_settings['show_as_link'] ) ? array( 'target' => '_blank' ) : array();
194
195
			} else {
196
197
				$link_atts = array(
198
					'rel' => sprintf( "%s-%s", $gv_class, $entry['id'] ),
199
					'target' => '_blank',
200
					'class' => 'thickbox',
201
				);
202
203
			}
204
205
			/**
206
			 * @filter `gravityview/fields/fileupload/link_atts` Modify the link attributes for a file upload field
207
			 * @param array|string $link_atts Array or attributes string
208
			 * @param array $field Current GravityView field array
209
			 */
210
			$link_atts = apply_filters( 'gravityview/fields/fileupload/link_atts', $link_atts, $gravityview_view->getCurrentField() );
211
212
			/**
213
			 * @filter `gravityview/fields/fileupload/disable_link` Filter to alter the default behaviour of wrapping images (or image names) with a link to the content object
214
			 * @since 1.5.1
215
			 * @param bool $disable_wrapped_link whether to wrap the content with a link to the content object.
216
			 * @param array $gravityview_view->field_data
217
			 * @see GravityView_API:field_value() for info about $gravityview_view->field_data
218
			 */
219
			$disable_wrapped_link = apply_filters( 'gravityview/fields/fileupload/disable_link', $disable_wrapped_link, $gravityview_view->getCurrentField() );
220
221
			// If the HTML output hasn't been overridden by the switch statement above, use the default format
222
			if( !empty( $content ) && empty( $disable_wrapped_link ) ) {
223
224
				/**
225
				 * Modify the link text (defaults to the file name)
226
				 *
227
				 * @since 1.7
228
				 *
229
				 * @param string $content The existing anchor content. Could be `<img>` tag, audio/video embed or the file name
230
				 * @param array $field GravityView array of the current field being processed
231
				 */
232
				$content = apply_filters( 'gravityview/fields/fileupload/link_content', $content, $gravityview_view->getCurrentField() );
233
234
                $content = gravityview_get_link( $link, $content, $link_atts );
235
			}
236
237
			$output_arr[] = array(
238
				'file_path' => $file_path,
239
				'content' => $content
240
			);
241
242
		} // End foreach loop
243
244
		/**
245
		 * @filter `gravityview/fields/fileupload/files_array` Modify the files array
246
		 * @since 1.7
247
		 * @param array $output_arr Associative array of files \n
248
		 *  @type string $file_path The path to the file as stored in Gravity Forms \n
249
		 *  @type string $content The generated output for the file \n
250
		 * @param array $field GravityView array of the current field being processed
251
		 */
252
		$output_arr = apply_filters( 'gravityview/fields/fileupload/files_array', $output_arr, $gravityview_view->getCurrentField() );
253
254
		return $output_arr;
255
	}
256
257
}
258
259
new GravityView_Field_FileUpload;
260