Completed
Push — develop ( f33cb6...e8781c )
by Gennady
15:41 queued 09:44
created

GravityView_API   F

Complexity

Total Complexity 89

Size/Duplication

Total Lines 655
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 81.08%

Importance

Changes 0
Metric Value
dl 0
loc 655
ccs 150
cts 185
cp 0.8108
rs 1.945
c 0
b 0
f 0
wmc 89
lcom 1
cbo 10

13 Methods

Rating   Name   Duplication   Size   Complexity  
C field_label() 0 74 10
A replace_variables() 0 3 1
A field_width() 0 17 4
B field_class() 0 40 7
A field_html_attr_id() 0 18 5
A field_value() 0 4 1
A entry_link_html() 0 26 5
B no_results() 0 42 9
F directory_link() 0 97 21
A get_custom_entry_slug() 0 20 2
B get_entry_slug() 0 61 8
A entry_create_custom_slug() 0 18 2
C entry_link() 0 71 14

How to fix   Complexity   

Complex Class

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

1
<?php
2
/**
3
 * GravityView template tags API
4
 *
5
 * @package   GravityView
6
 * @license   GPL2+
7
 * @author    Katz Web Services, Inc.
8
 * @link      http://gravityview.co
9
 * @copyright Copyright 2014, Katz Web Services, Inc.
10
 *
11
 * @since 1.0.0
12
 */
13
14
class GravityView_API {
15
16
	/**
17
	 * Fetch Field Label
18
	 *
19
	 * @deprecated Use \GV\Field::get_label()
20
	 *
21
	 * @access public
22
	 * @static
23
	 * @param array $field GravityView field array
24
	 * @param array $entry Gravity Forms entry array
25
	 * @param boolean $force_show_label Whether to always show the label, regardless of field settings
26
	 * @return string
27
	 */
28 3
	public static function field_label( $field, $entry = array(), $force_show_label = false ) {
29
30 3
		$gravityview_view = GravityView_View::getInstance();
31
32 3
		$form = $gravityview_view->getForm();
33
34 3
		if ( defined( 'DOING_GRAVITYVIEW_TESTS' ) && ! empty( $GLOBALS['GravityView_API_field_label_override'] ) ) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
35
			/** Allow to fall through for back compatibility testing purposes. */
36
		} else {
37 3
			return \GV\Mocks\GravityView_API_field_label( $form, $field, $entry, $force_show_label );
38
		}
39
40 1
		$label = '';
41
42 1
		if( !empty( $field['show_label'] ) || $force_show_label ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
43
44 1
			$label = $field['label'];
45
46
			// Support Gravity Forms 1.9+
47 1
			if( class_exists( 'GF_Field' ) ) {
48
49 1
				$field_object = RGFormsModel::get_field( $form, $field['id'] );
50
51 1
				if( $field_object ) {
52
53 1
					$input = GFFormsModel::get_input( $field_object, $field['id'] );
54
55
					// This is a complex field, with labels on a per-input basis
56 1
					if( $input ) {
57
58
						// Does the input have a custom label on a per-input basis? Otherwise, default label.
59 1
						$label = ! empty( $input['customLabel'] ) ? $input['customLabel'] : $input['label'];
60
61
					} else {
62
63
						// This is a field with one label
64 1
						$label = $field_object->get_field_label( true, $field['label'] );
65
66
					}
67
68
				}
69
70
			}
71
72
			// Use Gravity Forms label by default, but if a custom label is defined in GV, use it.
73 1
			if ( !empty( $field['custom_label'] ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
74
75 1
				$label = self::replace_variables( $field['custom_label'], $form, $entry );
76
77
			}
78
79
			/**
80
			 * @filter `gravityview_render_after_label` Append content to a field label
81
			 * @param[in,out] string $appended_content Content you can add after a label. Empty by default.
82
			 * @param[in] array $field GravityView field array
83
			 */
84 1
			$label .= apply_filters( 'gravityview_render_after_label', '', $field );
85
86
		} // End $field['show_label']
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% 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...
87
88
		/**
89
		 * @filter `gravityview/template/field_label` Modify field label output
90
		 * @since 1.7
91
		 * @param[in,out] string $label Field label HTML
92
		 * @param[in] array $field GravityView field array
93
		 * @param[in] array $form Gravity Forms form array
94
		 * @param[in] array $entry Gravity Forms entry array
95
		 *
96
		 * @deprecated Use the context-aware version `gravityview/template/field/label`
97
		 */
98 1
		$label = apply_filters( 'gravityview/template/field_label', $label, $field, $form, $entry );
99
100 1
		return $label;
101
	}
102
103
	/**
104
	 * Alias for GravityView_Merge_Tags::replace_variables()
105
	 *
106
	 * @see GravityView_Merge_Tags::replace_variables() Moved in 1.8.4
107
	 * @since 1.22.4 - Added $nl2br, $format, $aux_data args
108
	 *
109
	 * @param  string     $text         Text to replace variables in
110
	 * @param  array      $form         GF Form array
111
	 * @param  array      $entry        GF Entry array
112
	 * @param  bool       $url_encode   Pass return value through `url_encode()`
113
	 * @param  bool       $esc_html     Pass return value through `esc_html()`
114
	 * @param  bool       $nl2br        Convert newlines to <br> HTML tags
115
	 * @param  string     $format       The format requested for the location the merge is being used. Possible values: html, text or url.
116
	 * @param  array      $aux_data     Additional data to be used to replace merge tags {@see https://www.gravityhelp.com/documentation/article/gform_merge_tag_data/}
117
	 * @return string                   Text with variables maybe replaced
118
	 */
119 23
	public static function replace_variables( $text, $form = array(), $entry = array(), $url_encode = false, $esc_html = true, $nl2br = true, $format = 'html', $aux_data = array() ) {
120 23
		return GravityView_Merge_Tags::replace_variables( $text, $form, $entry, $url_encode, $esc_html, $nl2br, $format, $aux_data );
121
	}
122
123
	/**
124
	 * Get column width from the field setting
125
	 *
126
	 * @since 1.9
127
	 *
128
	 * @param array $field Array of settings for the field
129
	 * @param string $format Format for width. "%" (default) will return
130
	 *
131
	 * @return string|null If not empty, string in $format format. Otherwise, null.
132
	 */
133 25
	public static function field_width( $field, $format = '%d%%' ) {
134
135 25
		$width = NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
136
137 25
		if( !empty( $field['width'] ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
138 1
			$width = absint( $field['width'] );
139
140
			// If using percentages, limit to 100%
141 1
			if( '%d%%' === $format && $width > 100 ) {
142 1
				$width = 100;
143
			}
144
145 1
			$width = sprintf( $format, $width );
146
		}
147
148 25
		return $width;
149
	}
150
151
	/**
152
	 * Fetch Field class
153
	 *
154
	 * @access public
155
	 * @static
156
	 * @param mixed $field
157
	 * @return string
158
	 */
159 26
	public static function field_class( $field, $form = NULL, $entry = NULL ) {
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
160 26
		$classes = array();
161
162 26
		if( !empty( $field['custom_class'] ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
163
164 2
            $custom_class = $field['custom_class'];
165
166 2
            if( !empty( $entry ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
167
168
                // We want the merge tag to be formatted as a class. The merge tag may be
169
                // replaced by a multiple-word value that should be output as a single class.
170
                // "Office Manager" will be formatted as `.OfficeManager`, not `.Office` and `.Manager`
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% 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...
171 2
                add_filter('gform_merge_tag_filter', 'sanitize_html_class');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
172
173 2
                $custom_class = self::replace_variables( $custom_class, $form, $entry);
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
174
175
                // And then we want life to return to normal
176 2
                remove_filter('gform_merge_tag_filter', 'sanitize_html_class');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
177
            }
178
179
			// And now we want the spaces to be handled nicely.
180 2
			$classes[] = gravityview_sanitize_html_class( $custom_class );
181
182
		}
183
184 26
		if(!empty($field['id'])) {
0 ignored issues
show
introduced by
No space after opening parenthesis is prohibited
Loading history...
introduced by
Expected 1 space before "!"; 0 found
Loading history...
introduced by
Expected 1 space after "!"; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
introduced by
No space before closing parenthesis is prohibited
Loading history...
185 26
			if( !empty( $form ) && !empty( $form['id'] ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
186 26
				$form_id = '-'.$form['id'];
187
			} else {
188
				// @deprecated path. Form should always be given.
189
				gravityview()->log->warning( 'GravityView_View::getInstance() legacy API called' );
190
				$gravityview_view = GravityView_View::getInstance();
191
				$form_id = $gravityview_view->getFormId() ? '-'. $gravityview_view->getFormId() : '';
192
			}
193
194 26
			$classes[] = 'gv-field'.$form_id.'-'.$field['id'];
195
		}
196
197 26
		return esc_attr(implode(' ', $classes));
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
198
	}
199
200
	/**
201
	 * Fetch Field HTML ID
202
	 *
203
	 * @since 1.11
204
	 *
205
	 * @access public
206
	 * @static
207
	 * @param array $field GravityView field array passed to gravityview_field_output()
208
	 * @param array $form Gravity Forms form array, if set.
209
	 * @param array $entry Gravity Forms entry array
210
	 * @return string Sanitized unique HTML `id` attribute for the field
211
	 */
212 24
	public static function field_html_attr_id( $field, $form = array(), $entry = array() ) {
0 ignored issues
show
Unused Code introduced by
The parameter $entry 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...
213 24
		$id = $field['id'];
214
215 24
		if ( ! empty( $id ) ) {
216 24
			if ( ! empty( $form ) && ! empty( $form['id'] ) ) {
217 24
				$form_id = '-' . $form['id'];
218
			} else {
219
				// @deprecated path. Form should always be given.
220
				gravityview()->log->warning( 'GravityView_View::getInstance() legacy API called' );
221
				$gravityview_view = GravityView_View::getInstance();
222
				$form_id = $gravityview_view->getFormId() ? '-' . $gravityview_view->getFormId() : '';
223
			}
224
225 24
			$id = 'gv-field' . $form_id . '-' . $field['id'];
226
		}
227
228 24
		return esc_attr( $id );
229
	}
230
231
232
	/**
233
	 * Given an entry and a form field id, calculate the entry value for that field.
234
	 *
235
	 * @deprecated Use \GV\Field_Template::render() or the more low-level \GV\Field::get_value()
236
	 *
237
	 * @access public
238
	 * @param array $entry
239
	 * @param array $field
0 ignored issues
show
Bug introduced by
There is no parameter named $field. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
240
	 * @return null|string
241
	 */
242 3
	public static function field_value( $entry, $field_settings, $format = 'html' ) {
243 3
		gravityview()->log->notice( '\GravityView_API::field_value is deprecated. Use \GV\Field_Template::render() or \GV\Field::get_value()' );
244 3
		return \GV\Mocks\GravityView_API_field_value( $entry, $field_settings, $format );
0 ignored issues
show
Deprecated Code introduced by
The function GV\Mocks\GravityView_API_field_value() has been deprecated with message: Use \GV\Field_Template::render()

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
245
	}
246
247
	/**
248
	 * Generate an anchor tag that links to an entry.
249
	 *
250
	 * @since 1.6
251
	 * @see GVCommon::get_link_html()
252
	 *
253
	 * @param string $anchor_text The text or HTML inside the link
254
	 * @param array $entry Gravity Forms entry array
255
	 * @param array|string $passed_tag_atts Attributes to be added to the anchor tag, such as `title` or `rel`.
256
	 * @param array $field_settings Array of field settings. Optional, but passed to the `gravityview_field_entry_link` filter
257
	 *
258
	 * @since 2.0
259
	 * @param int $base_id The post or the view that this entry is linked from.
260
	 *
261
	 * @return string|null Returns HTML for an anchor link. Null if $entry isn't defined or is missing an ID.
262
	 */
263 3
	public static function entry_link_html( $entry = array(), $anchor_text = '', $passed_tag_atts = array(), $field_settings = array(), $base_id = null ) {
264
265 3
		if ( empty( $entry ) || ! is_array( $entry ) || ! isset( $entry['id'] ) ) {
266 1
			gravityview()->log->debug( 'Entry not defined; returning null', array( 'data' => $entry ) );
267 1
			return NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
268
		}
269
270 3
		$href = self::entry_link( $entry, $base_id );
271
272 3
		if( '' === $href ) {
273
			return NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
274
		}
275
276 3
		$link = gravityview_get_link( $href, $anchor_text, $passed_tag_atts );
277
278
		/**
279
		 * @filter `gravityview_field_entry_link` Modify the link HTML
280
		 * @param string $link HTML output of the link
281
		 * @param string $href URL of the link
282
		 * @param array  $entry The GF entry array
283
		 * @param  array $field_settings Settings for the particular GV field
284
		 */
285 3
		$output = apply_filters( 'gravityview_field_entry_link', $link, $href, $entry, $field_settings );
286
287 3
		return $output;
288
	}
289
290
	/**
291
	 * Get the "No Results" text depending on whether there were results.
292
	 * @param  boolean     $wpautop Apply wpautop() to the output?
293
	 *
294
	 * @since 2.0
295
	 * @param \GV\Template_Context $context The context
296
	 *
297
	 * @return string               HTML of "no results" text
298
	 */
299 9
	public static function no_results( $wpautop = true, $context = null ) {
300 9
		$is_search = false;
301
302 9
		if ( $context instanceof \GV\Template_Context ) {
303 7
			if ( $context->request->is_search() ) {
304 7
				$search = true;
305
			}
306
		} else {
307 2
			$gravityview_view = GravityView_View::getInstance();
308
309 2
			if( $gravityview_view && ( $gravityview_view->curr_start || $gravityview_view->curr_end || $gravityview_view->curr_search ) ) {
0 ignored issues
show
Documentation introduced by
The property curr_start does not exist on object<GravityView_View>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read 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.");
        }
    }

}

If the property has read access only, you can use the @property-read 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...
Documentation introduced by
The property curr_end does not exist on object<GravityView_View>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read 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.");
        }
    }

}

If the property has read access only, you can use the @property-read 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...
Documentation introduced by
The property curr_search does not exist on object<GravityView_View>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read 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.");
        }
    }

}

If the property has read access only, you can use the @property-read 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...
310 1
				$is_search = true;
311
			}
312
		}
313
314 9
		if ( $is_search ) {
315 1
			$output = __( 'This search returned no results.', 'gravityview' );
316
		} else {
317 9
			$output = __( 'No entries match your request.', 'gravityview' );
318
		}
319
320
		/**
321
		 * @filter `gravitview_no_entries_text` Modify the text displayed when there are no entries.
322
		 * @param string $output The existing "No Entries" text
323
		 * @param boolean $is_search Is the current page a search result, or just a multiple entries screen?
324
		 * @return string The modified text.
325
		 * @deprecated Use `gravityview/template/text/no_entries`
326
		 */
327 9
		$output = apply_filters( 'gravitview_no_entries_text', $output, $is_search );
328
329
		/**
330
		 * @filter `gravityview/template/text/no_entries` Modify the text displayed when there are no entries.
331
		 * @since 2.0
332
		 * @param string $output The existing "No Entries" text
333
		 * @param boolean $is_search Is the current page a search result, or just a multiple entries screen?
334
		 * @param \GV\Template_Context $context The context.
335
		 * @return string The modified text.
336
		 */
337 9
		$output = apply_filters( 'gravityview/template/text/no_entries', $output, $is_search, $context );
338
339 9
		return $wpautop ? wpautop( $output ) : $output;
340
	}
341
342
	/**
343
	 * Generate a URL to the Directory context
344
	 *
345
	 * Uses `wp_cache_get` and `wp_cache_get` (since 1.3) to speed up repeated requests to get permalink, which improves load time. Since we may be doing this hundreds of times per request, it adds up!
346
	 *
347
	 * @param int $post_id Post ID
348
	 * @param boolean $add_query_args Add pagination and sorting arguments
349
	 *
350
	 * @since 2.0
351
	 * @param \GV\Template_Context $context The context this is being used in.
352
	 *
353
	 * @return string      Permalink to multiple entries view
354
	 */
355 23
	public static function directory_link( $post_id = NULL, $add_query_args = true, $context = null ) {
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
356 23
		global $post;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
357
358 23
		if ( empty( $post_id ) ) {
359
			// DataTables passes the Post ID
360 14
			if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
361
				$post_id = \GV\Utils::_POST( 'post_id', false );
362
			} else {
363 14
				if ( $context instanceof \GV\Template_Context ) {
364
					// Shortcodes, embeds
365 11
					if ( is_a( $post, 'WP_Post' ) ) {
366 1
						$post_id = $post->ID;
367
368
					// Actual views
369
					} else {
370 11
						$post_id = $context->view ? $context->view->ID : false;
371
					}
372
				} else {
373
					/** @deprecated path of execution */
374 3
					$gravityview_view = GravityView_View::getInstance();
375
376
					// The Post ID has been passed via the shortcode
377 3
					if ( ! empty( $gravityview_view ) && $gravityview_view->getPostId() ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $gravityview_view->getPostId() of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
378 2
						$post_id = $gravityview_view->getPostId();
379
					} else {
380
						// This is a GravityView post type
381 1
						if ( GravityView_frontend::getInstance()->isGravityviewPostType() ) {
382
							$post_id = isset( $gravityview_view ) ? $gravityview_view->getViewId() : $post->ID;
383
						} else {
384
							// This is an embedded GravityView; use the embedded post's ID as the base.
385 1
							if ( GravityView_frontend::getInstance()->isPostHasShortcode() && is_a( $post, 'WP_Post' ) ) {
386
								$post_id = $post->ID;
387 1
							} elseif ( $gravityview_view->getViewId() ) {
388
								// The GravityView has been embedded in a widget or in a template, and
389
								// is not in the current content. Thus, we defer to the View's own ID.
390
								$post_id = $gravityview_view->getViewId();
391
							}
392
						}
393
					}
394
				}
395
			}
396
		}
397
398
		// No post ID, get outta here.
399 23
		if ( empty( $post_id ) ) {
400 1
			return null;
401
		}
402
403
		// If we've saved the permalink in memory, use it
404
		// @since 1.3
405 22
		$link = wp_cache_get( 'gv_directory_link_'.$post_id );
406
407 22
		if ( (int) $post_id === (int) get_option( 'page_on_front' ) ) {
408
			$link = home_url();
409
		}
410
411 22
		if ( empty( $link ) ) {
412 22
			$link = get_permalink( $post_id );
413
414
			// If not yet saved, cache the permalink.
415
			// @since 1.3
416 22
			wp_cache_set( 'gv_directory_link_'.$post_id, $link );
417
		}
418
419
		// Deal with returning to proper pagination for embedded views
420 22
		if ( $link && $add_query_args ) {
421
422 17
			$args = array();
423
424 17
			if( $pagenum = \GV\Utils::_GET( 'pagenum' ) ) {
425 1
				$args['pagenum'] = intval( $pagenum );
426
			}
427
428 17
			if( $sort = \GV\Utils::_GET( 'sort' ) ) {
429
				$args['sort'] = $sort;
430
				$args['dir'] = \GV\Utils::_GET( 'dir' );
431
			}
432
433 17
			$link = add_query_arg( $args, $link );
434
		}
435
436
		/**
437
		 * @filter `gravityview_directory_link` Modify the URL to the View "directory" context
438
		 * @since 1.19.4
439
		 * @param string $link URL to the View's "directory" context (Multiple Entries screen)
440
		 * @param int $post_id ID of the post to link to. If the View is embedded, it is the post or page ID
441
		 */
442 22
		$link = apply_filters( 'gravityview_directory_link', $link, $post_id );
443
444
		/**
445
		 * @filter `gravityview/view/links/directory` Modify the URL to the View "directory" context
446
		 * @since 2.0
447
		 * @param string $link URL to the View's "directory" context (Multiple Entries screen)
448
		 * @param \GV\Template_Context $context 
449
		 */
450 22
		return apply_filters( 'gravityview/view/links/directory', $link, $context );
451
	}
452
453
	/**
454
	 * Calculate an *unique* hash for an entry based on the entry ID
455
	 *
456
	 * This allows you to be more discrete as to the number of the entry - if you don't want users to know that you have made a certain number of sales, for example, or that their entry in the giveaway is entry #3.
457
	 *
458
	 * The hashed value MUST be unique, otherwise multiple entries will share the same URL, which leads to obvious problems.
459
	 *
460
	 * @param  int|string $id Entry ID to generate the hash for.
461
	 * @param  array  $entry        Entry data passed to provide additional information when generating the hash. Optional - don't rely on it being available.
462
	 * @return string               Hashed unique value for entry
463
	 */
464 2
	private static function get_custom_entry_slug( $id, $entry = array() ) {
465
466
		// Generate an unique hash to use as the default value
467 2
		$slug = substr( wp_hash( $id, 'gravityview'.$id ), 0, 8 );
468
469
		/**
470
		 * @filter `gravityview_entry_slug` Modify the unique hash ID generated, if you want to improve usability or change the format. This will allow for custom URLs, such as `{entryid}-{first-name}` or even, if unique, `{first-name}-{last-name}`
471
		 * @param string $hash Existing hash generated by GravityView
472
		 * @param  string $id The entry ID
473
		 * @param  array $entry Entry data array. May be empty.
474
		 */
475 2
		$slug = apply_filters( 'gravityview_entry_slug', $slug, $id, $entry );
476
477
		// Make sure we have something - use the original ID as backup.
478 2
		if( empty( $slug ) ) {
479
			$slug = $id;
480
		}
481
482 2
		return sanitize_title( $slug );
483
	}
484
485
	/**
486
	 * Get the entry slug for the entry. By default, it is the entry ID.
487
	 *
488
	 *
489
	 * @see gravityview_get_entry()
490
	 * @uses GravityView_API::get_custom_entry_slug() If using custom slug, gets the custom slug value
491
	 * @since 1.4
492
	 * @param  int|string $id_or_string ID of the entry, or custom slug string
493
	 * @param  array  $entry        Gravity Forms Entry array, optional. Used only to provide data to customize the `gravityview_entry_slug` filter
494
	 * @return string               Unique slug ID, passed through `sanitize_title()`
495
	 */
496 68
	public static function get_entry_slug( $id_or_string, $entry = array() ) {
497
498
		/**
499
		 * Default: use the entry ID as the unique identifier
500
		 */
501 68
		$slug = $id_or_string;
502
503
		/**
504
		 * @filter `gravityview_custom_entry_slug` Whether to enable and use custom entry slugs.
505
		 * @param boolean True: Allow for slugs based on entry values. False: always use entry IDs (default)
506
		 */
507 68
		$custom = apply_filters( 'gravityview_custom_entry_slug', false );
508
509
		// If we're using custom slug...
510 68
		if ( $custom ) {
511
512
			// Get the entry hash
513 2
			$hash = self::get_custom_entry_slug( $id_or_string, $entry );
514
515
			// Cache the slugs
516 2
			static $cache = array();
517
518 2
			if ( ! isset( $cache[ $id_or_string ] ) ) {
519 2
				global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
520
521 2
				if ( version_compare( GFFormsModel::get_database_version(), '2.3-dev-1', '>=' ) ) {
522 2
					$table = GFFormsModel::get_entry_meta_table_name();
523 2
					$column = 'entry_id';
524
				} else {
525
					$table = RGFormsModel::get_lead_meta_table_name();
526
					$column = 'lead_id';
527
				}
528
529 2
				$results = $wpdb->get_results( $wpdb->prepare( "SELECT $column, meta_value FROM $table WHERE form_id = (SELECT form_id FROM $table WHERE $column = %d LIMIT 1) AND meta_key = 'gravityview_unique_id'", $id_or_string ) );
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
530
531 2
				if ( $results ) {
532
					$cache = array_replace( $cache, array_combine( wp_list_pluck( $results, $column ), wp_list_pluck( $results, 'meta_value' ) ) );
533
				}
534
535 2
				if ( ! isset( $cache[ $id_or_string ] ) ) {
536 2
					$cache[ $id_or_string ] = false;
537
				}
538
			}
539
540 2
			$value = $cache[ $id_or_string ];
541
542
			// If it does have a hash set, and the hash is expected, use it.
543
			// This check allows users to change the hash structure using the
544
			// gravityview_entry_hash filter and have the old hashes expire.
545 2
			if ( empty( $value ) || $value !== $hash ) {
546 2
				gravityview()->log->debug( 'Setting hash for entry {entry}: {hash}', array( 'entry' => $id_or_string, 'hash' => $hash ) );
547 2
				gform_update_meta( $id_or_string, 'gravityview_unique_id', $hash, \GV\Utils::get( $entry, 'form_id' ) );
548
			}
549
550 2
			$slug = $hash;
551
552 2
			unset( $value, $hash );
553
		}
554
555 68
		return sanitize_title( $slug );
556
	}
557
558
    /**
559
     * If using the entry custom slug feature, make sure the new entries have the custom slug created and saved as meta
560
     *
561
     * Triggered by add_action( 'gform_entry_created', array( 'GravityView_API', 'entry_create_custom_slug' ), 10, 2 );
562
     *
563
     * @param $entry array Gravity Forms entry object
564
     * @param $form array Gravity Forms form object
565
     */
566
    public static function entry_create_custom_slug( $entry, $form ) {
0 ignored issues
show
Unused Code introduced by
The parameter $form 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...
567
        /**
568
         * @filter `gravityview_custom_entry_slug` On entry creation, check if we are using the custom entry slug feature and update the meta
569
         * @param boolean $custom Should we process the custom entry slug?
570
         */
571
        $custom = apply_filters( 'gravityview_custom_entry_slug', false );
572
        if( $custom ) {
573
            // create the gravityview_unique_id and save it
574
575
            // Get the entry hash
576
            $hash = self::get_custom_entry_slug( $entry['id'], $entry );
577
578
	        gravityview()->log->debug( 'Setting hash for entry {entry_id}: {hash}', array( 'entry_id' => $entry['id'], 'hash' => $hash ) );
579
580
            gform_update_meta( $entry['id'], 'gravityview_unique_id', $hash, \GV\Utils::get( $entry, 'form_id' ) );
581
582
        }
583
    }
584
585
586
587
588
	/**
589
	 * return href for single entry
590
	 * @param  array|int $entry   Entry array or entry ID
591
	 * @param  int|null $post_id If wanting to define the parent post, pass a post ID
592
	 * @param boolean $add_directory_args True: Add args to help return to directory; False: only include args required to get to entry {@since 1.7.3}
593
	 * @return string          Link to the entry with the directory parent slug, or empty string if embedded post or View doesn't exist
594
	 */
595 7
	public static function entry_link( $entry, $post_id = NULL, $add_directory_args = true ) {
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
596
597 7
		if ( ! empty( $entry ) && ! is_array( $entry ) ) {
598
			$entry = GVCommon::get_entry( $entry );
599 7
		} else if( empty( $entry ) ) {
600
			// @deprecated path
601
			$entry = GravityView_frontend::getInstance()->getEntry();
602
		}
603
604
		// Second parameter used to be passed as $field; this makes sure it's not an array
605 7
		if ( ! is_numeric( $post_id ) ) {
606 1
			$post_id = NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
607
		}
608
609
		// Get the permalink to the View
610 7
		$directory_link = self::directory_link( $post_id, false );
611
612
		// No post ID? Get outta here.
613 7
		if ( empty( $directory_link ) ) {
614 1
			return '';
615
		}
616
617 6
		$query_arg_name = \GV\Entry::get_endpoint_name();
618
619 6
		$entry_slug = self::get_entry_slug( $entry['id'], $entry );
620
621 6
		if ( get_option('permalink_structure') && !is_preview() ) {
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
introduced by
Expected 1 space after "!"; 0 found
Loading history...
622
623
			$args = array();
624
625
			/**
626
			 * Make sure the $directory_link doesn't contain any query otherwise it will break when adding the entry slug.
627
			 * @since 1.16.5
628
			 */
629
			$link_parts = explode( '?', $directory_link );
630
631
			$query = !empty( $link_parts[1] ) ? '?'.$link_parts[1] : '';
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
632
633
			$directory_link = trailingslashit( $link_parts[0] ) . $query_arg_name . '/'. $entry_slug .'/' . $query;
634
635
		} else {
636
637 6
			$args = array( $query_arg_name => $entry_slug );
638
		}
639
640
		/**
641
		 * @since 1.7.3
642
		 */
643 6
		if ( $add_directory_args ) {
644
645 6
			if ( ! empty( $_GET['pagenum'] ) ) {
646
				$args['pagenum'] = intval( $_GET['pagenum'] );
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
647
			}
648
649
			/**
650
			 * @since 1.7
651
			 */
652 6
			if ( $sort = \GV\Utils::_GET( 'sort' ) ) {
653
				$args['sort'] = $sort;
654
				$args['dir'] = \GV\Utils::_GET( 'dir' );
655
			}
656
657
		}
658
659 6
		if ( class_exists( 'GravityView_View_Data' ) && GravityView_View_Data::getInstance()->has_multiple_views() ) {
0 ignored issues
show
Deprecated Code introduced by
The method GravityView_View_Data::has_multiple_views() has been deprecated.

This method has been deprecated.

Loading history...
660
			$args['gvid'] = gravityview_get_view_id();
661
		}
662
663 6
		return add_query_arg( $args, $directory_link );
664
665
	}
666
667
668
}
669
670
671
// inside loop functions
672
673
/**
674
 * @deprecated Use \GV\Field::get_label()
675
 */
676
function gv_label( $field, $entry = NULL ) {
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
677 2
	return GravityView_API::field_label( $field, $entry );
0 ignored issues
show
Deprecated Code introduced by
The method GravityView_API::field_label() has been deprecated with message: Use \GV\Field::get_label()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
678
}
679
680
function gv_class( $field, $form = NULL, $entry = array() ) {
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
681 25
	return GravityView_API::field_class( $field, $form, $entry  );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces before closing bracket; 2 found
Loading history...
682
}
683
684
/**
685
 * Generate a CSS class to be added to the wrapper <div> of a View
686
 *
687
 * @since 1.5.4
688
 * @since 1.16 Added $echo parameter.
689
 * @since 2.0 Added $context parameter.
690
 *
691
 * @param string $passed_css_class Default: `gv-container gv-container-{view id}`. If View is hidden until search, adds ` hidden`
692
 * @param boolean $echo Whether to echo the output. Default: true
693
 * @param \GV\Template_Context $context The template context.
694
 *
695
 * @return string CSS class, sanitized by gravityview_sanitize_html_class()
696
 */
697
function gv_container_class( $passed_css_class = '', $echo = true, $context = null ) {
698 28
	if ( $context instanceof \GV\Template_Context ) {
699 26
		$hide_until_searched = false;
700 26
		$total_entries = 0;
701 26
		$view_id = 0;
702 26
		if ( $context->view ) {
703 26
			$view_id = $context->view->ID;
704 26
			if( $context->view->settings->get( 'hide_until_searched' ) ) {
705 4
				$hide_until_searched = ( empty( $context->entry ) && ! $context->request->is_search() );
706
			}
707
		}
708 26
		if ( $context->entries ) {
709 16
			$total_entries = $context->entries->total();
710 11
		} else if ( $context->entry ) {
711 26
			$total_entries = 1;
712
		}
713
	} else {
714
		/** @deprecated legacy execution path */
715 3
		$view_id = GravityView_View::getInstance()->getViewId();
716 3
		$hide_until_searched = GravityView_View::getInstance()->isHideUntilSearched();
717 3
		$total_entries = GravityView_View::getInstance()->getTotalEntries();
718
	}
719
720 28
	$passed_css_class = trim( $passed_css_class );
721
722 28
	$default_css_class = ! empty( $view_id ) ? sprintf( 'gv-container gv-container-%d', $view_id ) : 'gv-container';
723
724 28
	if ( $hide_until_searched ) {
725 4
		$default_css_class .= ' hidden';
726
	}
727
728 28
	if ( 0 === $total_entries ) {
729 7
		$default_css_class .= ' gv-container-no-results';
730
	}
731
732 28
	$css_class = trim( $passed_css_class . ' '. $default_css_class );
733
734
	/**
735
	 * @filter `gravityview/render/container/class` Modify the CSS class to be added to the wrapper <div> of a View
736
	 * @since 1.5.4
737
	 * @param[in,out] string $css_class Default: `gv-container gv-container-{view id}`. If View is hidden until search, adds ` hidden`. If the View has no results, adds `gv-container-no-results`
738
	 * @since 2.0
739
	 * @param \GV\Template_Context $context The context.
740
	 */
741 28
	$css_class = apply_filters( 'gravityview/render/container/class', $css_class, $context );
742
743 28
	$css_class = gravityview_sanitize_html_class( $css_class );
744
745 28
	if ( $echo ) {
746 28
		echo $css_class;
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$css_class'
Loading history...
747
	}
748
749 28
	return $css_class;
750
}
751
752
/**
753
 * @deprecated Use \GV\Field_Template::render()
754
 */
755
function gv_value( $entry, $field ) {
756
757 2
	$value = GravityView_API::field_value( $entry, $field );
0 ignored issues
show
Deprecated Code introduced by
The method GravityView_API::field_value() has been deprecated with message: Use \GV\Field_Template::render() or the more low-level \GV\Field::get_value()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
758
759 2
	if( $value === '' ) {
760
		/**
761
		 * @filter `gravityview_empty_value` What to display when a field is empty
762
		 * @param string $value (empty string)
763
		 */
764 1
		$value = apply_filters( 'gravityview_empty_value', '' );
765
	}
766
767 2
	return $value;
768
}
769
770
function gv_directory_link( $post = NULL, $add_pagination = true, $context = null ) {
0 ignored issues
show
introduced by
Overridding WordPress globals is prohibited
Loading history...
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
771 12
	return GravityView_API::directory_link( $post, $add_pagination, $context );
772
}
773
774
function gv_entry_link( $entry, $post_id = NULL ) {
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
775 2
	return GravityView_API::entry_link( $entry, $post_id );
776
}
777
778
function gv_no_results( $wpautop = true, $context = null ) {
779 8
	return GravityView_API::no_results( $wpautop, $context );
780
}
781
782
/**
783
 * Generate HTML for the back link from single entry view
784
 * @since 1.0.1
785
 * @since 2.0
786
 * @param \GV\Template_Context $context The context this link is being displayed from.
787
 * @return string|null      If no GV post exists, null. Otherwise, HTML string of back link.
788
 */
789
function gravityview_back_link( $context = null ) {
790
791 11
	$href = gv_directory_link( null, true, $context );
792
793
	/**
794
	 * @filter `gravityview_go_back_url` Modify the back link URL
795
	 * @since 1.17.5
796
	 * @see gv_directory_link() Generated the original back link
797
	 * @param string $href Existing label URL
798
	 * @deprecated Use `gravityview/template/links/back/url`
799
	 */
800 11
	$href = apply_filters( 'gravityview_go_back_url', $href );
801
802
	/**
803
	 * @filter `gravityview/template/links/back/url` Modify the back link URL
804
	 * @since 2.0
805
	 * @see gv_directory_link() Generated the original back link
806
	 * @param string $href Existing label URL
807
	 * @param \GV\Template_Context The context.
808
	 */
809 11
	$href = apply_filters( 'gravityview/template/links/back/url', $href, $context );
810
811 11
	if ( empty( $href ) ) {
812 3
		return NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
813
	}
814
815 9
	if ( $context instanceof \GV\Template_Context ) {
816 9
		$view_id = $context->view->ID;
817 9
		$view_label = $context->template->get_back_label();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class GV\Template as the method get_back_label() does only exist in the following sub-classes of GV\Template: GV\Entry_Legacy_Template, GV\Entry_List_Template, GV\Entry_Table_Template, GV\Entry_Template. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
818
	} else {
819
		/** @deprecated legacy path */
820
		$gravityview_view = GravityView_View::getInstance();
821
		$view_id = $gravityview_view->getViewId();
822
		$view_label = $gravityview_view->getBackLinkLabel() ? $gravityview_view->getBackLinkLabel() : false;
0 ignored issues
show
Deprecated Code introduced by
The method GravityView_View::getBackLinkLabel() has been deprecated with message: Use $template->get_back_label();

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
823
	}
824
825
	/** Default */
826 9
	$label = $view_label ? $view_label : __( '&larr; Go back', 'gravityview' );
827
828
	/**
829
	 * @filter `gravityview_go_back_label` Modify the back link text
830
	 * @since 1.0.9
831
	 * @param string $label Existing label text
832
	 * @deprecated Use `gravityview/template/links/back/label`
833
	 */
834 9
	$label = apply_filters( 'gravityview_go_back_label', $label );
835
836
	/**
837
	 * @filter `gravityview_go_back_label` Modify the back link text
838
	 * @since 2.0
839
	 * @see gv_directory_link() Generated the original back link
840
	 * @param string $label Existing label text
841
	 * @param \GV\Template_Context The context.
842
	 */
843 9
	$label = apply_filters( 'gravityview/template/links/back/label', $label, $context );
844
845 9
	$link = gravityview_get_link( $href, esc_html( $label ), array(
846 9
		'data-viewid' => $view_id,
847
	) );
848
849 9
	return $link;
850
}
851
852
/**
853
 * Handle getting values for complex Gravity Forms fields
854
 *
855
 * If the field is complex, like a product, the field ID, for example, 11, won't exist. Instead,
856
 * it will be 11.1, 11.2, and 11.3. This handles being passed 11 and 11.2 with the same function.
857
 *
858
 * @since 1.0.4
859
 * @param  array      $entry    GF entry array
860
 * @param  string      $field_id [description]
861
 * @param  string 	$display_value The value generated by Gravity Forms
862
 * @return string                Value
863
 */
864
function gravityview_get_field_value( $entry, $field_id, $display_value ) {
865
866 6
	if( floatval( $field_id ) === floor( floatval( $field_id ) ) ) {
867
868
		// For the complete field value as generated by Gravity Forms
869 3
		return $display_value;
870
871
	} else {
872
873
		// For one part of the address (City, ZIP, etc.)
874 6
		return isset( $entry[ $field_id ] ) ? $entry[ $field_id ] : '';
875
876
	}
877
878
}
879
880
/**
881
 * Take a passed CSV of terms and generate a linked list of terms
882
 *
883
 * Gravity Forms passes categories as "Name:ID" so we handle that using the ID, which
884
 * is more accurate than checking the name, which is more likely to change.
885
 *
886
 * @param  string      $value    Existing value
887
 * @param  string      $taxonomy Type of term (`post_tag` or `category`)
888
 * @return string                CSV of linked terms
889
 */
890
function gravityview_convert_value_to_term_list( $value, $taxonomy = 'post_tag' ) {
891
892 1
	$output = array();
893
894 1
	if ( is_array( $value ) ) {
895 1
		$terms = array_filter( array_values( $value ), 'strlen' );
896
	} else {
897 1
		$terms = explode( ', ', $value );
898
	}
899
900 1
	foreach ($terms as $term_name ) {
0 ignored issues
show
introduced by
No space after opening parenthesis is prohibited
Loading history...
901
902
		// If we're processing a category,
903 1
		if( $taxonomy === 'category' ) {
0 ignored issues
show
introduced by
Found "=== '". Use Yoda Condition checks, you must
Loading history...
904
905
			// Use rgexplode to prevent errors if : doesn't exist
906 1
			list( $term_name, $term_id ) = rgexplode( ':', $term_name, 2 );
907
908
			// The explode was succesful; we have the category ID
909 1
			if( !empty( $term_id )) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
introduced by
No space before closing parenthesis is prohibited
Loading history...
910 1
				$term = get_term_by( 'id', $term_id, $taxonomy );
911
			} else {
912
			// We have to fall back to the name
913 1
				$term = get_term_by( 'name', $term_name, $taxonomy );
914
			}
915
916
		} else {
917
			// Use the name of the tag to get the full term information
918 1
			$term = get_term_by( 'name', $term_name, $taxonomy );
919
		}
920
921
		// There's still a tag/category here.
922 1
		if( $term ) {
923
924 1
			$term_link = get_term_link( $term, $taxonomy );
925
926
			// If there was an error, continue to the next term.
927 1
			if ( is_wp_error( $term_link ) ) {
928
			    continue;
929
			}
930
931 1
			$output[] = gravityview_get_link( $term_link, esc_html( $term->name ) );
932
		}
933
	}
934
935 1
	return implode(', ', $output );
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
936
}
937
938
/**
939
 * Get the links for post_tags and post_category output based on post ID
940
 * @param  int      $post_id  The ID of the post
941
 * @param  boolean     $link     Add links or no?
942
 * @param  string      $taxonomy Taxonomy of term to fetch.
943
 * @return string                String with terms
944
 */
945
function gravityview_get_the_term_list( $post_id, $link = true, $taxonomy = 'post_tag' ) {
946
947 1
	$output = get_the_term_list( $post_id, $taxonomy, NULL, ', ' );
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
948
949 1
	if( empty( $link ) ) {
950 1
		return strip_tags( $output);
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
951
	}
952
953 1
	return $output;
954
955
}
956
957
958
/**
959
 * Get all views processed so far for the current page load
960
 *
961
 * @see  GravityView_View_Data::add_view()
962
 * @return array Array of View data, each View data with `id`, `view_id`, `form_id`, `template_id`, `atts`, `fields`, `widgets`, `form` keys.
963
 */
964
function gravityview_get_current_views() {
965
966 1
	$fe = GravityView_frontend::getInstance();
967
968
	// Solve problem when loading content via admin-ajax.php
969 1
	if( ! $fe->getGvOutputData() ) {
970
971 1
		gravityview()->log->debug( 'gv_output_data not defined; parsing content.' );
972
973 1
		$fe->parse_content();
974
	}
975
976
	// Make 100% sure that we're dealing with a properly called situation
977 1
	if( !is_a( $fe->getGvOutputData(), 'GravityView_View_Data' ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
978
979
		gravityview()->log->debug( 'gv_output_data not an object or get_view not callable.', array( 'data' => $fe->getGvOutputData() ) );
980
981
		return array();
982
	}
983
984 1
	return $fe->getGvOutputData()->get_views();
0 ignored issues
show
Deprecated Code introduced by
The method GravityView_View_Data::get_views() has been deprecated.

This method has been deprecated.

Loading history...
985
}
986
987
/**
988
 * Get data for a specific view
989
 *
990
 * @see  GravityView_View_Data::get_view()
991
 * @return array View data with `id`, `view_id`, `form_id`, `template_id`, `atts`, `fields`, `widgets`, `form` keys.
992
 */
993
function gravityview_get_current_view_data( $view_id = 0 ) {
994
995
	$fe = GravityView_frontend::getInstance();
996
997
	// If not set, grab the current view ID
998
	if ( empty( $view_id ) ) {
999
		$view_id = $fe->get_context_view_id();
1000
	}
1001
1002
	if ( ! $fe->getGvOutputData() ) { return array(); }
1003
1004
	return $fe->getGvOutputData()->get_view( $view_id );
0 ignored issues
show
Deprecated Code introduced by
The method GravityView_View_Data::get_view() has been deprecated.

This method has been deprecated.

Loading history...
1005
}
1006
1007
// Templates' hooks
1008
function gravityview_before() {
1009
	/**
1010
	 * @action `gravityview/template/before` Append content to the view.
1011
	 * @param object $gravityview The $gravityview object available in templates.
1012
	 */
1013 27
	if ( count( $args = func_get_args() ) ) {
1014 25
		$gravityview = reset( $args );
1015 25
		if ( $gravityview instanceof \GV\Template_Context ) {
1016
			/**
1017
			 * @action `gravityview/template/before` Prepend content to the view.
1018
			 * @param \GV\Template_Context $gravityview The $gravityview object available in templates.
1019
			 */
1020 25
			do_action( 'gravityview/template/before', $gravityview );
1021
1022
			/**
1023
			 * @deprecated Use `gravityview/template/before`
1024
			 */
1025 25
			return do_action( 'gravityview_before', $gravityview->view->ID );
1026
		}
1027
	}
1028
1029
	/**
1030
	 * @action `gravityview_before` Prepend content to the View container `<div>`
1031
	 * @deprecated Use `gravityview/template/before`.
1032
	 * @param int $view_id The ID of the View being displayed
1033
	 */
1034 2
	do_action( 'gravityview_before', gravityview_get_view_id() );
1035 2
}
1036
1037
function gravityview_header() {
1038
	/**
1039
	 * @action `gravityview/template/header` Append content to the view.
1040
	 * @param object $gravityview The $gravityview object available in templates.
1041
	 */
1042 23
	if ( count( $args = func_get_args() ) ) {
1043 21
		$gravityview = reset( $args );
1044 21
		if ( $gravityview instanceof \GV\Template_Context ) {
1045
			/**
1046
			 * @action `gravityview/template/header` Prepend content to the view container <div>.
1047
			 * @param \GV\Template_Context $gravityview The $gravityview object available in templates.
1048
			 */
1049 21
			do_action( 'gravityview/template/header', $gravityview );
1050
1051
			/**
1052
			 * @deprecated Use `gravityview/template/header`
1053
			 */
1054 21
			return do_action( 'gravityview_header', $gravityview->view->ID );
1055
		}
1056
	}
1057
1058
	/**
1059
	 * @action `gravityview_header` Prepend content to the View container `<div>`
1060
	 * @deprecated Use `gravityview/template/header`.
1061
	 * @param int $view_id The ID of the View being displayed
1062
	 */
1063 2
	do_action( 'gravityview_header', gravityview_get_view_id() );
1064 2
}
1065
1066
function gravityview_footer() {
1067
	/**
1068
	 * @action `gravityview/template/footer` Append content to the view.
1069
	 * @param object $gravityview The $gravityview object available in templates.
1070
	 */
1071 23
	if ( count( $args = func_get_args() ) ) {
1072 21
		$gravityview = reset( $args );
1073 21
		if ( $gravityview instanceof \GV\Template_Context ) {
1074
			/**
1075
			 * @action `gravityview/template/footer` Prepend outside of the view container <div>.
1076
			 * @param \GV\Template_Context $gravityview The $gravityview object available in templates.
1077
			 */
1078 21
			do_action( 'gravityview/template/footer', $gravityview );
1079
1080
			/**
1081
			 * @deprecated Use `gravityview/template/footer`
1082
			 */
1083 21
			return do_action( 'gravityview_footer', $gravityview->view->ID );
1084
		}
1085
	}
1086
1087
	/**
1088
	 * @action `gravityview_after` Display content after a View. Used to render footer widget areas. Rendered outside the View container `<div>`
1089
	 * @deprecated Use `gravityview/template/footer`.
1090
	 * @param int $view_id The ID of the View being displayed
1091
	 */
1092 2
	do_action( 'gravityview_footer', gravityview_get_view_id() );
1093 2
}
1094
1095
function gravityview_after() {
1096 27
	if ( count( $args = func_get_args() ) ) {
1097 25
		$gravityview = reset( $args );
1098 25
		if ( $gravityview instanceof \GV\Template_Context ) {
1099
			/**
1100
			 * @action `gravityview/template/after` Append content to the view.
1101
			 * @param \GV\Template_Context $gravityview The $gravityview object available in templates.
1102
			 */
1103 25
			do_action( 'gravityview/template/after', $gravityview );
1104
1105
			/**
1106
			 * @deprecated Use `gravityview/template/after`
1107
			 */
1108 25
			do_action( 'gravityview_after', $gravityview->view->ID );
1109
1110 25
			return;
1111
		}
1112
	}
1113
1114
	/**
1115
	 * @action `gravityview_after` Append content to the View container `<div>`
1116
	 * @deprecated Use `gravityview/template/after`
1117
	 * @param int $view_id The ID of the View being displayed
1118
	 */
1119 2
	do_action( 'gravityview_after', gravityview_get_view_id() );
1120 2
}
1121
1122
/**
1123
 * Get the current View ID being rendered
1124
 *
1125
 * @global GravityView_View $gravityview_view
1126
 *
1127
 * @return int View ID, if exists. `0` if `GravityView_View` doesn't exist, like in the admin, or no View is set.
1128
 */
1129
function gravityview_get_view_id() {
1130
1131 2
	if ( ! class_exists( 'GravityView_View' ) ) {
1132
		return 0;
1133
	}
1134
1135 2
	return GravityView_View::getInstance()->getViewId();
1136
}
1137
1138
/**
1139
 * Returns the current GravityView context, or empty string if not GravityView
1140
 *
1141
 * - Returns empty string on GravityView archive pages
1142
 * - Returns empty string on archive pages containing embedded Views
1143
 * - Returns empty string for embedded Views, not 'directory'
1144
 * - Returns empty string for embedded entries (oEmbed or [gventry]), not 'single'
1145
 * - Returns 'single' when viewing a [gravityview] shortcode-embedded single entry
1146
 *
1147
 * @global GravityView_View $gravityview_view
1148
 * @deprecated since 2.0.6.2 Use `gravityview()->request`
1149
 * @return string View context "directory", "single", "edit", or empty string if not GravityView
1150
 */
1151
function gravityview_get_context() {
1152 4
	global $wp_query;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
1153
1154 4
	if ( isset( $wp_query ) && $wp_query->post_count > 1 ) {
1155
		return '';
1156
	}
1157
1158
	/**
1159
	 * @filter `gravityview_is_edit_entry` Whether we're currently on the Edit Entry screen \n
1160
	 * The Edit Entry functionality overrides this value.
1161
	 * @param boolean $is_edit_entry
1162
	 */
1163 4
	$is_edit_entry = apply_filters( 'gravityview_is_edit_entry', false );
1164
1165 4
	if ( $is_edit_entry ) {
1166
		return 'edit';
1167 4
	} else if ( gravityview()->request->is_entry() ) {
1168 1
		return 'single';
1169 3
	} else if ( gravityview()->request->is_view() ) {
1170 2
		return 'directory';
1171
	}
1172
1173 1
	return '';
1174
}
1175
1176
1177
/**
1178
 * Return an array of files prepared for output. Wrapper for GravityView_Field_FileUpload::get_files_array()
1179
 *
1180
 * Processes files by file type and generates unique output for each.
1181
 *
1182
 * Returns array for each file, with the following keys:
1183
 *
1184
 * `file_path` => The file path of the file, with a line break
1185
 * `html` => The file output HTML formatted
1186
 *
1187
 * @see GravityView_Field_FileUpload::get_files_array()
1188
 *
1189
 * @since  1.2
1190
 * @param  string $value    Field value passed by Gravity Forms. String of file URL, or serialized string of file URL array
1191
 * @param  string $gv_class Field class to add to the output HTML
1192
 * @since  2.0
1193
 * @param  \GV\Template_Context $context The context
1194
 * @return array           Array of file output, with `file_path` and `html` keys (see comments above)
1195
 */
1196
function gravityview_get_files_array( $value, $gv_class = '', $context = null ) {
1197
	/** @define "GRAVITYVIEW_DIR" "../" */
1198
1199 1
	if( !class_exists( 'GravityView_Field' ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
1200
		include_once( GRAVITYVIEW_DIR .'includes/fields/class-gravityview-field.php' );
1201
	}
1202
1203 1
	if( !class_exists( 'GravityView_Field_FileUpload' ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
1204
		include_once( GRAVITYVIEW_DIR .'includes/fields/class-gravityview-field-fileupload.php' );
1205
	}
1206
1207 1
	return GravityView_Field_FileUpload::get_files_array( $value, $gv_class, $context );
1208
}
1209
1210
/**
1211
 * Generate a mapping link from an address
1212
 *
1213
 * The address should be plain text with new line (`\n`) or `<br />` line breaks separating sections
1214
 *
1215
 * @todo use GF's field get_export_value() instead
1216
 *
1217
 * @see https://gravityview.co/support/documentation/201608159 Read how to modify the link
1218
 * @param  string $address Address
1219
 * @return string          URL of link to map of address
1220
 */
1221
function gravityview_get_map_link( $address ) {
1222
1223
	$address_qs = str_replace( array( '<br />', "\n" ), ' ', $address ); // Replace \n with spaces
1224
	$address_qs = urlencode( $address_qs );
1225
1226
	$url = "https://maps.google.com/maps?q={$address_qs}";
1227
1228
	$link_text = esc_html__( 'Map It', 'gravityview' );
1229
1230
	$link = gravityview_get_link( $url, $link_text, 'class=map-it-link' );
1231
1232
	/**
1233
	 * @filter `gravityview_map_link` Modify the map link generated. You can use a different mapping service, for example.
1234
	 * @param[in,out]  string $link Map link
1235
	 * @param[in] string $address Address to generate link for
1236
	 * @param[in] string $url URL generated by the function
1237
	 */
1238
	$link = apply_filters( 'gravityview_map_link', $link, $address, $url );
1239
1240
	return $link;
1241
}
1242
1243
1244
/**
1245
 * Output field based on a certain html markup
1246
 *
1247
 *   markup - string to be used on a sprintf statement.
1248
 *      Use:
1249
 *         {{label}} - field label
1250
 *         {{value}} - entry field value
1251
 *         {{class}} - field class
1252
 *
1253
 *   wpautop - true will filter the value using wpautop function
1254
 *
1255
 * @since  1.1.5
1256
 * @param  array $passed_args Associative array with field data. `field` and `form` are required.
1257
 * @since  2.0
1258
 * @param  \GV\Template_Context The template context.
1259
 * @return string Field output. If empty value and hide empty is true, return empty.
1260
 */
1261
function gravityview_field_output( $passed_args, $context = null ) {
1262
	$defaults = array(
1263 24
		'entry' => null,
1264
		'field' => null,
1265
		'form' => null,
1266
		'hide_empty' => true,
1267
		'markup' => '<div id="{{ field_id }}" class="{{ class }}">{{ label }}{{ value }}</div>',
1268
		'label_markup' => '',
1269
		'wpautop' => false,
1270
		'zone_id' => null,
1271
	);
1272
1273 24
	$args = wp_parse_args( $passed_args, $defaults );
1274
1275
	/**
1276
	 * @filter `gravityview/field_output/args` Modify the args before generation begins
1277
	 * @since 1.7
1278
	 * @param array $args Associative array; `field` and `form` is required.
1279
	 * @param array $passed_args Original associative array with field data. `field` and `form` are required.
1280
	 * @since 2.0
1281
	 * @param \GV\Template_Context $context The context.
1282
	 * @deprecated
1283
	 */
1284 24
	$args = apply_filters( 'gravityview/field_output/args', $args, $passed_args, $context );
1285
1286
	/**
1287
	 * @filter `gravityview/template/field_output/context` Modify the context before generation begins.
1288
	 * @since 2.0
1289
	 * @param[in,out] \GV\Template_Context $context The context.
1290
	 * @param array $args The sanitized arguments, these should not be trusted any longer.
1291
	 * @param array $passed_args The passed arguments, these should not be trusted any longer.
1292
	 */
1293 24
	$context = apply_filters( 'gravityview/template/field_output/context', $context, $args, $passed_args );
1294
1295 24
	if ( $context instanceof \GV\Template_Context ) {
1296 22
		if ( ! $context->field || ! $context->view || ! $context->view->form ) {
1297
			gravityview()->log->error( 'Field or form are empty.', array( 'data' => array( $context->field, $context->view->form ) ) );
1298 22
			return '';
1299
		}
1300
	} else {
1301
		// @deprecated path
1302
		// Required fields.
1303 2
		if ( empty( $args['field'] ) || empty( $args['form'] ) ) {
1304
			gravityview()->log->error( 'Field or form are empty.', array( 'data' => $args ) );
1305
			return '';
1306
		}
1307
	}
1308
1309 24
	if ( $context instanceof \GV\Template_Context ) {
1310 22
		$entry = $args['entry'] ? : ( $context->entry ? $context->entry->as_entry() : array() );
1311 22
		$field = $args['field'] ? : ( $context->field ? $context->field->as_configuration() : array() );
1312 22
		$form = $args['form'] ? : ( $context->view->form ? $context->view->form->form : array() );
0 ignored issues
show
Documentation introduced by
The property $form is declared private in GV\Form. 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...
1313
	} else {
1314
		// @deprecated path
1315 2
		$entry = empty( $args['entry'] ) ? array() : $args['entry'];
1316 2
		$field = $args['field'];
1317 2
		$form = $args['form'];
1318
	}
1319
1320
	/**
1321
	 * Create the content variables for replacing.
1322
	 * @since 1.11
1323
	 */
1324
	$placeholders = array(
1325 24
		'value' => '',
1326
		'width' => '',
1327
		'width:style' => '',
1328
		'label' => '',
1329
		'label_value' => '',
1330
		'class' => '',
1331
		'field_id' => '',
1332
	);
1333
1334 24
	if ( $context instanceof \GV\Template_Context ) {
1335 22
		$placeholders['value'] = \GV\Utils::get( $args, 'value', '' );
1336
	} else {
1337
		// @deprecated path
1338 2
		$placeholders['value'] = gv_value( $entry, $field );
0 ignored issues
show
Deprecated Code introduced by
The function gv_value() has been deprecated with message: Use \GV\Field_Template::render()

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
1339
	}
1340
1341
	// If the value is empty and we're hiding empty, return empty.
1342 24
	if ( $placeholders['value'] === '' && ! empty( $args['hide_empty'] ) ) {
1343 5
		return '';
1344
	}
1345
1346 24
	if ( $placeholders['value'] !== '' && ! empty( $args['wpautop'] ) ) {
1347 5
		$placeholders['value'] = wpautop( $placeholders['value'] );
1348
	}
1349
1350
	// Get width setting, if exists
1351 24
	$placeholders['width'] = GravityView_API::field_width( $field );
1352
1353
	// If replacing with CSS inline formatting, let's do it.
1354 24
	$placeholders['width:style'] = GravityView_API::field_width( $field, 'width:' . $placeholders['width'] . '%;' );
1355
1356
	// Grab the Class using `gv_class`
1357 24
	$placeholders['class'] = gv_class( $field, $form, $entry );
1358 24
	$placeholders['field_id'] = GravityView_API::field_html_attr_id( $field, $form, $entry );
1359
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
1360
1361
	// Get field label if needed
1362 24
	if ( ! empty( $args['label_markup'] ) && ! empty( $args['field']['show_label'] ) ) {
1363 1
		$placeholders['label'] = str_replace( array( '{{label}}', '{{ label }}' ), '<span class="gv-field-label">{{ label_value }}</span>', $args['label_markup'] );
1364
	}
1365
1366 24
	if ( $context instanceof \GV\Template_Context ) {
1367 22
		$placeholders['label_value'] = \GV\Utils::get( $args, 'label' );
1368
	} else {
1369
		// Default Label value
1370 2
		$placeholders['label_value'] = gv_label( $field, $entry );
0 ignored issues
show
Deprecated Code introduced by
The function gv_label() has been deprecated with message: Use \GV\Field::get_label()

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
1371
	}
1372
1373 24
	if ( empty( $placeholders['label'] ) && ! empty( $placeholders['label_value'] ) ){
1374 24
		$placeholders['label'] = '<span class="gv-field-label">{{ label_value }}</span>';
1375
	}
1376
1377
	/**
1378
	 * @filter `gravityview/field_output/pre_html` Allow Pre filtering of the HTML
1379
	 * @since 1.11
1380
	 * @param string $markup The HTML for the markup
1381
	 * @param array $args All args for the field output
1382
	 * @since 2.0
1383
	 * @param \GV\Template_Context $context The context.
1384
	 */
1385 24
	$html = apply_filters( 'gravityview/field_output/pre_html', $args['markup'], $args, $context );
1386
1387
	/**
1388
	 * @filter `gravityview/field_output/open_tag` Modify the opening tags for the template content placeholders
1389
	 * @since 1.11
1390
	 * @param string $open_tag Open tag for template content placeholders. Default: `{{`
1391
	 * @since 2.0
1392
	 * @param \GV\Template_Context $context The context.
1393
	 */
1394 24
	$open_tag = apply_filters( 'gravityview/field_output/open_tag', '{{', $args, $context );
1395
1396
	/**
1397
	 * @filter `gravityview/field_output/close_tag` Modify the closing tags for the template content placeholders
1398
	 * @since 1.11
1399
	 * @param string $close_tag Close tag for template content placeholders. Default: `}}`
1400
	 * @since 2.0
1401
	 * @param \GV\Template_Context $context The context.
1402
	 */
1403 24
	$close_tag = apply_filters( 'gravityview/field_output/close_tag', '}}', $args, $context );
1404
1405
	/**
1406
	 * Loop through each of the tags to replace and replace both `{{tag}}` and `{{ tag }}` with the values
1407
	 * @since 1.11
1408
	 */
1409 24
	foreach ( $placeholders as $tag => $value ) {
1410
1411
		// If the tag doesn't exist just skip it
1412 24
		if ( false === strpos( $html, $open_tag . $tag . $close_tag ) && false === strpos( $html, $open_tag . ' ' . $tag . ' ' . $close_tag ) ){
1413 24
			continue;
1414
		}
1415
1416
		// Array to search
1417
		$search = array(
1418 24
			$open_tag . $tag . $close_tag,
1419 24
			$open_tag . ' ' . $tag . ' ' . $close_tag,
1420
		);
1421
1422
		/**
1423
		 * `gravityview/field_output/context/{$tag}` Allow users to filter content on context
1424
		 * @since 1.11
1425
		 * @param string $value The content to be shown instead of the {{tag}} placeholder
1426
		 * @param array $args Arguments passed to the function
1427
		 * @since 2.0
1428
		 * @param \GV\Template_Context $context The context.
1429
		 */
1430 24
		$value = apply_filters( 'gravityview/field_output/context/' . $tag, $value, $args, $context );
1431
1432
		// Finally do the replace
1433 24
		$html = str_replace( $search, $value, $html );
1434
	}
1435
1436
	/**
1437
	 * @filter `gravityview_field_output` Modify field HTML output
1438
	 * @param string $html Existing HTML output
1439
	 * @param array $args Arguments passed to the function
1440
	 * @since 2.0
1441
	 * @param \GV\Template_Context $context The context.
1442
	 */
1443 24
	$html = apply_filters( 'gravityview_field_output', $html, $args, $context );
1444
1445
	/**
1446
	 * @filter `gravityview/field_output/html` Modify field HTML output
1447
	 * @param string $html Existing HTML output
1448
	 * @param array $args Arguments passed to the function
1449
	 * @since 2.0
1450
	 * @param \GV\Template_Context $context The context.
1451
	 */
1452 24
	$html = apply_filters( 'gravityview/field_output/html', $html, $args, $context );
1453
1454
	/** @since 2.0.8 Remove unused atts */
1455 24
	$html = str_replace( array( ' style=""', ' class=""', ' id=""' ), '', $html );
1456
1457 24
	return $html;
1458
}
1459