Completed
Pull Request — master (#1029)
by Gennady
28:29 queued 08:25
created

_mocks.php ➔ GravityView_frontend_get_view_entries()   B

Complexity

Conditions 5
Paths 9

Size

Total Lines 60
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 5.0812

Importance

Changes 0
Metric Value
cc 5
eloc 21
nc 9
nop 4
dl 0
loc 60
ccs 23
cts 27
cp 0.8519
crap 5.0812
rs 8.6961
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 15 and the first side effect is on line 665.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
namespace GV\Mocks;
3
4
/**
5
 * This file contains mock code for deprecated functions.
6
 */
7
8
/**
9
 * @see \GravityView_View_Data::add_view
10
 * @internal
11
 * @since 2.0
12
 *
13
 * @return array|false The old array data, or false on error.
14
 */
15
function GravityView_View_Data_add_view( $view_id, $atts, $_this ) {
0 ignored issues
show
Coding Style introduced by
The function name GravityView_View_Data_add_view is in camel caps, but expected _gravity_view_view_data_add_view instead as per the coding standard.
Loading history...
16
	/** Handle array of IDs. */
17
	if ( is_array( $view_id ) ) {
18
		foreach ( $view_id as $id ) {
19
			call_user_func( __FUNCTION__, $id, $atts, $_this );
20
		}
21
22
		if ( ! $_this->views->count() ) {
23
			return array();
24
		}
25
26
		return array_combine(
27
			array_map( function( $view ) { return $view->ID; }, $_this->views->all() ),
28
			array_map( function( $view ) { return $view->as_data(); }, $_this->views->all() )
29
		);
30
	}
31
32
	/** View has been set already. */
33
	if ( $view = $_this->views->get( $view_id ) ) {
34
		do_action( 'gravityview_log_debug', sprintf( 'GravityView_View_Data[add_view] Returning; View #%s already exists.', $view_id ) );
35
		return $view->as_data();
36
	}
37
38
	$view = \GV\View::by_id( $view_id );
39
	if ( ! $view ) {
40
		do_action( 'gravityview_log_debug', sprintf( 'GravityView_View_Data[add_view] Returning; View #%s does not exist.', $view_id ) );
41
		return false;
42
	}
43
44
	/** Doesn't have a connected form. */
45
	if ( ! $view->form ) {
46
		do_action( 'gravityview_log_debug', sprintf( 'GravityView_View_Data[add_view] Returning; Post ID #%s does not have a connected form.', $view_id ) );
47
		return false;
48
	}
49
50
	/** Update the settings */
51
	if ( is_array( $atts ) ) {
52
		$view->settings->update( $atts );
53
	}
54
55
	$_this->views->add( $view );
56
57
	return $view->as_data();
0 ignored issues
show
Deprecated Code introduced by
The method GV\View::as_data() has been deprecated.

This method has been deprecated.

Loading history...
58
}
59
60
/**
61
 * @see \GravityView_frontend::get_view_entries
62
 * @internal
63
 * @since 2.0
64
 *
65
 * @return array The old associative array data as returned by
66
 *  \GravityView_frontend::get_view_entries(), the paging parameters
67
 *  and a total count of all entries.
68
 */
69
function GravityView_frontend_get_view_entries( $args, $form_id, $parameters, $count ) {
0 ignored issues
show
Coding Style introduced by
The function name GravityView_frontend_get_view_entries is in camel caps, but expected _gravity_view_frontend_get_view_entries instead as per the coding standard.
Loading history...
70 1
	$form = \GV\GF_Form::by_id( $form_id );
71
72
	/**
73
	 * Kick off all advanced filters.
74
	 *
75
	 * Parameters and criteria are pretty much the same thing here, just
76
	 *  different naming, where `$parameters` are the initial parameters
77
	 *  calculated for hte view, and `$criteria` are the filtered ones
78
	 *  retrieved via `GVCommon::calculate_get_entries_criteria`.
79
	 */
80 1
	$criteria = \GVCommon::calculate_get_entries_criteria( $parameters, $form->ID );
81
82 1
	do_action( 'gravityview_log_debug', '[gravityview_get_entries] Final Parameters', $criteria );
83
84
	/** ...and all the (now deprectated) filters that usually follow `gravityview_get_entries` */
85
86
	/**
87
	 * @deprecated
88
	 * Do not use this filter anymore.
89
	 */
90 1
	$entries = apply_filters( 'gravityview_before_get_entries', null, $criteria, $parameters, $count );
91 1
	if ( ! is_null( $entries ) ) {
92
		/**
93
		 * We've been given an entries result that we can return,
94
		 *  just set the paging and we're good to go.
95
		 */
96 1
		$paging = \GV\Utils::get( $parameters, 'paging' );
97
	} else {
98 1
		$entries = new \GV\Entry_Collection();
99 1
		if ( $view = \GV\View::by_id( \GV\Utils::get( $args, 'id' ) ) ) {
100 1
			$view->settings->update( $args );
101 1
			$entries = $view->get_entries( gravityview()->request );
102
		}
103 1
104 1
		$page = \GV\Utils::get( $parameters['paging'], 'current_page' ) ?
105
			: ( ( ( $parameters['paging']['offset'] - $view->settings->get( 'offset' ) ) / $parameters['paging']['page_size'] ) + 1 );
106
107 1
		/** Set paging, count and unwrap the entries. */
108 1
		$paging = array(
109 1
			'offset' => ( $page - 1 ) * $view->settings->get( 'page_size' ),
110 1
			'page_size' => $view->settings->get( 'page_size' ),
111 1
		);
112
		/**
113
		 * GF_Query does not subtract the offset, we have to subtract it ourselves.
114 1
		 */
115
		$count = $entries->total() - ( gravityview()->plugin->supports( \GV\Plugin::FEATURE_GFQUERY ) ? $view->settings->get( 'offset' ) : 0 );
116
		$entries = array_map( function( $e ) { return $e->as_entry(); }, $entries->all() );
117
	}
118 1
119 1
	/** Just one more filter, for compatibility's sake! */
120 1
121
	/**
122
	 * @deprecated
123 1
	 * Do not use this filter anymore.
124 1
	 */
125
	$entries = apply_filters_ref_array( 'gravityview_entries', array( $entries, $criteria, $parameters, &$count ) );
126
127
	return array( $entries, $paging, $count );
128
}
129 1
130 1
/**
131
 * The old function does a bit too much, not only does it retrieve
132 1
 *  the value for a field, but it also renders some output. We are
133
 *  stubbing the plain value part of it, the rendering will follow once
134
 *  our field renderers are ready.
135
 *
136
 * @see \GravityView_API::field_value
137
 * @deprecated Use \GV\Field_Template::render()
138
 * @internal
139
 * @since 2.0
140
 *
141
 * @return null|string The value of a field in an entry.
142 1
 */
143
function GravityView_API_field_value( $entry, $field_settings, $format ) {
0 ignored issues
show
Unused Code introduced by
The parameter $format 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...
Coding Style introduced by
The function name GravityView_API_field_value is in camel caps, but expected _gravity_view_a_p_i_field_value instead as per the coding standard.
Loading history...
144 1
	if ( empty( $entry['form_id'] ) || empty( $field_settings['id'] ) ) {
145
		gravityview()->log->error( 'No entry or field_settings[id] supplied', array( 'data' => array( func_get_args() ) ) );
146
		return null;
147
	}
148
149
	if ( ! empty( $entry['_multi'] ) && ! empty( $field_settings['form_id'] ) && ! empty( $entry['_multi'][ $field_settings['form_id'] ] ) ) {
150
		$entry = $entry['_multi'][ $field_settings['form_id'] ];
151
	}
152
153
	if ( empty( $entry['id'] ) || ! $entry = \GV\GF_Entry::by_id( $entry['id'] ) ) {
154
		gravityview()->log->error( 'Invalid \GV\GF_Entry supplied', array( 'data' => $entry ) );
155
		return null;
156
	}
157
158
	/**
159
	 * Determine the source backend.
160
	 *
161 3
	 * Fields with a numeric ID are Gravity Forms ones.
162 1
	 */
163 1
	$source = is_numeric( $field_settings['id'] ) ? \GV\Source::BACKEND_GRAVITYFORMS : \GV\Source::BACKEND_INTERNAL;;
164
165
	/** Initialize the future field. */
166 3
	switch ( $source ):
167 2
		/** The Gravity Forms backend. */
168
		case \GV\Source::BACKEND_GRAVITYFORMS:
169
			if ( ! $form = \GV\GF_Form::by_id( $entry['form_id'] ) ) {
170 3
				gravityview()->log->error( 'No form Gravity Form found for entry', array( 'data' => $entry ) );
171
				return null;
172
			}
173
174
			if ( ! $field = $form::get_field( $form, $field_settings['id'] ) ) {
175
				return null;
176
			}
177
178
			break;
179
180 3
		/** Our internal backend. */
181
		case \GV\Source::BACKEND_INTERNAL:
182
			if ( ! $field = \GV\Internal_Source::get_field( $field_settings['id'] ) ) {
183
				return null;
184
			}
185 3
186 3
			break;
187
188
		/** An unidentified backend. */
189
		default:
190
			gravityview()->log->error( 'Could not determine source for entry', array( 'data' => array( func_get_args() ) ) );
191 3
			return null;
192
	endswitch;
193
194
	/** Add the field settings. */
195 3
	$field->update_configuration( $field_settings );
196
197
	$renderer = new \GV\Field_Renderer();
198 3
	return $renderer->render( $field, gravityview()->views->get(), $source == \GV\Source::BACKEND_GRAVITYFORMS ? $form : null, $entry, gravityview()->request );
0 ignored issues
show
Documentation introduced by
The property views does not exist on object<GV\Core>. 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...
Bug introduced by
The variable $form does not seem to be defined for all execution paths leading up to this point.

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
199 3
}
200
201
/**
202
 * Mock out the \GravityView_API::field_label method
203 3
 *
204
 * Uses the new \GV\Field::get_label methods
205
 *
206
 * @see \GravityView_API::field_label
207
 * @internal
208
 * @since 2.0
209
 *
210
 * @return string The label of a field in an entry.
211
 */
212 3
function GravityView_API_field_label( $form, $field_settings, $entry, $force_show_label = false ) {
0 ignored issues
show
Coding Style introduced by
The function name GravityView_API_field_label is in camel caps, but expected _gravity_view_a_p_i_field_label instead as per the coding standard.
Loading history...
213
214 3
	/** A bail condition. */
215 3
	$bail = function( $label, $field_settings, $entry, $force_show_label, $form ) {
216
		if ( ! empty( $field_settings['show_label'] ) || $force_show_label ) {
217
218
			$label = isset( $field_settings['label'] ) ? $field_settings['label'] : '';
219
220
			// Use Gravity Forms label by default, but if a custom label is defined in GV, use it.
221
			if ( ! empty( $field_settings['custom_label'] ) ) {
222
				$label = \GravityView_API::replace_variables( $field_settings['custom_label'], $form, $entry );
223
			}
224
225
			/**
226
			 * @filter `gravityview_render_after_label` Append content to a field label
227
			 * @param[in,out] string $appended_content Content you can add after a label. Empty by default.
228
			 * @param[in] array $field GravityView field array
229
			 */
230
			$label .= apply_filters( 'gravityview_render_after_label', '', $field_settings );
231
		}
232
233 2
		/**
234
		 * @filter `gravityview/template/field_label` Modify field label output
235 2
		 * @since 1.7
236
		 * @param[in,out] string $label Field label HTML
237
		 * @param[in] array $field GravityView field array
238 2
		 * @param[in] array $form Gravity Forms form array
239 1
		 * @param[in] array $entry Gravity Forms entry array
240
		 */
241
		$label = apply_filters( 'gravityview/template/field_label', $label, $field_settings, $form, $entry );
242
243
		return $label;
244
	};
245
246
	$label = '';
247 2
248
	if ( ! empty( $entry['_multi'] ) && ! empty( $field_settings['form_id'] ) && ! empty( $entry['_multi'][ $field_settings['form_id'] ] ) ) {
249
		$entry = $entry['_multi'][ $field_settings['form_id'] ];
250
		if ( $_form = \GV\GF_Form::by_id( $field_settings['form_id'] ) ) {
251
			$form = $_form->form;
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...
252
		}
253
	}
254
255
	if ( empty( $entry['form_id'] ) || empty( $field_settings['id'] ) ) {
256
		gravityview()->log->error( 'No entry or field_settings[id] supplied', array( 'data' => array( func_get_args() ) ) );
257
		return $bail( $label, $field_settings, $entry, $force_show_label, $form );
258 2
	}
259
260 2
	if ( empty( $entry['id'] ) || ! $gv_entry = \GV\GF_Entry::by_id( $entry['id'] ) ) {
261 3
		gravityview()->log->error( 'Invalid \GV\GF_Entry supplied', array( 'data' => $entry ) );
262
		return $bail( $label, $field_settings, $entry, $force_show_label, $form );
263 3
	}
264
265 3
	$entry = $gv_entry;
266 2
267 2
	/**
268 2
	 * Determine the source backend.
269
	 *
270
	 * Fields with a numeric ID are Gravity Forms ones.
271
	 */
272 3
	$source = is_numeric( $field_settings['id'] ) ? \GV\Source::BACKEND_GRAVITYFORMS : \GV\Source::BACKEND_INTERNAL;
273 2
274 2
	/** Initialize the future field. */
275
	switch ( $source ):
276
		/** The Gravity Forms backend. */
277 3
		case \GV\Source::BACKEND_GRAVITYFORMS:
278
			if ( ! $gf_form = \GV\GF_Form::by_id( $entry['form_id'] ) ) {
279
				gravityview()->log->error( 'No form Gravity Form found for entry', array( 'data' => $entry ) );
280
				return $bail( $label, $field_settings, $entry->as_entry(), $force_show_label, $form );
281
			}
282 3
283
			if ( ! $field = $gf_form::get_field( $gf_form, $field_settings['id'] ) ) {
284
				gravityview()->log->error( 'No field found for specified form and field ID #{field_id}', array( 'field_id' => $field_settings['id'], 'data' => $form ) );
285
				return $bail( $label, $field_settings, $entry->as_entry(), $force_show_label, $gf_form->form );
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...
286
			}
287
			if ( empty( $field_settings['show_label'] ) ) {
288
				/** The label never wins... */
289 3
				$field_settings['label'] = '';
290
			}
291
292
			break;
293
294 3
		/** Our internal backend. */
295 3
		case \GV\Source::BACKEND_INTERNAL:
296
			if ( ! $field = \GV\Internal_Source::get_field( $field_settings['id'] ) ) {
297
				return $bail( $label, $field_settings, $entry->as_entry(), $force_show_label, $form );
298
			}
299
			break;
300 3
301
		/** An unidentified backend. */
302
		default:
303
			gravityview()->log->error( 'Could not determine source for entry. Using empty field.', array( 'data' => array( func_get_args() ) ) );
304 3
			$field = new \GV\Field();
305
			break;
306 1
	endswitch;
307
308
	if( $force_show_label ) {
309 3
		$field_settings['show_label'] = '1';
310
	}
311
312 3
	/** Add the field settings. */
313 3
	$field->update_configuration( $field_settings );
314
315
	if ( ! empty( $field->show_label ) ) {
316 3
317
		$label = $field->get_label( null, isset( $gf_form ) ? $gf_form : null, $entry );
318
319
		/**
320
		 * @filter `gravityview_render_after_label` Append content to a field label
321
		 * @param[in,out] string $appended_content Content you can add after a label. Empty by default.
322
		 * @param[in] array $field GravityView field array
323
		 */
324
		$label .= apply_filters( 'gravityview_render_after_label', '', $field->as_configuration() );
325 3
326 1
	}
327
328
	/**
329
	 * @filter `gravityview/template/field_label` Modify field label output
330 3
	 * @since 1.7
331
	 * @param[in,out] string $label Field label HTML
332 3
	 * @param[in] array $field GravityView field array
333
	 * @param[in] array $form Gravity Forms form array
334 3
	 * @param[in] array $entry Gravity Forms entry array
335
	 */
336
	return apply_filters( 'gravityview/template/field_label', $label, $field->as_configuration(), isset( $gf_form ) ? $gf_form->form : $form, $entry->as_entry() );
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...
337
}
338
339
340
/**
341 3
 * A manager of legacy global states and contexts.
342
 *
343
 * Handles mocking of:
344
 * - \GravityView_View_Data
345
 * - \GravityView_View
346
 * - \GravityView_frontend
347
 *
348
 * Allows us to set a specific state globally using the old
349
 *  containers, then reset it. Useful for legacy code that keeps
350
 *  on depending on these variables.
351
 *
352
 * Some examples right now include template files, utility functions,
353 3
 *  some actions and filters that expect the old contexts to be set.
354
 */
355
final class Legacy_Context {
356
	private static $stack = array();
357
358
	/**
359
	 * Set the state depending on the provided configuration.
360
	 *
361
	 * Saves current global state and context.
362
	 *
363
	 * Configuration keys:
364
	 *
365
	 * - \GV\View	view:		sets \GravityView_View::atts, \GravityView_View::view_id,
366
	 *								 \GravityView_View::back_link_label
367
	 *								 \GravityView_frontend::context_view_id,
368
	 *								 \GravityView_View::form, \GravityView_View::form_id
369
	 * - \GV\Field	field:		sets \GravityView_View::_current_field, \GravityView_View::field_data,
370
	 * - \GV\Entry	entry:		sets \GravityView_View::_current_entry, \GravityView_frontend::single_entry,
371
	 *								 \GravityView_frontend::entry
372
	 * - \WP_Post	post:		sets \GravityView_View::post_id, \GravityView_frontend::post_id,
373
	 *								 \GravityView_frontend::is_gravityview_post_type,
374
	 *								 \GravityView_frontend::post_has_shortcode
375
	 * - array		paging:		sets \GravityView_View::paging
376
	 * - array		sorting:	sets \GravityView_View::sorting
377
	 * - array		template:	sets \GravityView_View::template_part_slug, \GravityView_View::template_part_name
378
	 *
379
	 * - boolean	in_the_loop sets $wp_actions['loop_start'] and $wp_query::in_the_loop
380
	 *
381
	 * also:
382
	 *
383
	 * - \GV\Request	request:	sets \GravityView_frontend::is_search, \GravityView_frontend::single_entry,
384
	 *									 \GravityView_View::context, \GravityView_frontend::entry
385
	 *
386
	 * - \GV\View_Collection	views:		sets \GravityView_View_Data::views
387
	 * - \GV\Field_Collection	fields:		sets \GravityView_View::fields
388
	 * - \GV\Entry_Collection	entries:	sets \GravityView_View::entries, \GravityView_View::total_entries
389
	 *
390
	 * and automagically:
391
	 *
392
	 * - \GravityView_View		data:		sets \GravityView_frontend::gv_output_data
393
	 *
394
	 * @param array $configuration The configuration.
395
	 *
396
	 * @return void
397
	 */
398
	public static function push( $configuration ) {
399
		array_push( self::$stack, self::freeze() );
400
		self::load( $configuration );
401
	}
402
403
	/**
404
	 * Restores last saved state and context.
405
	 *
406
	 * @return void
407
	 */
408
	public static function pop() {
409
		self::thaw( array_pop( self::$stack ) );
410
	}
411
412
	/**
413
	 * Serializes the current configuration as needed.
414
	 *
415 22
	 * @return array The configuration.
416 22
	 */
417 22
	public static function freeze() {
418 22
		global $wp_actions, $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...
419
420
		return array(
421
			'\GravityView_View::atts' => \GravityView_View::getInstance()->getAtts(),
422
			'\GravityView_View::view_id' => \GravityView_View::getInstance()->getViewId(),
423
			'\GravityView_View::back_link_label' => \GravityView_View::getInstance()->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...
424
			'\GravityView_View_Data::views' => \GravityView_View_Data::getInstance()->views,
425 22
			'\GravityView_View::entries' => \GravityView_View::getInstance()->getEntries(),
426 22
			'\GravityView_View::form' => \GravityView_View::getInstance()->getForm(),
427 22
			'\GravityView_View::form_id' => \GravityView_View::getInstance()->getFormId(),
428
			'\GravityView_View::context' => \GravityView_View::getInstance()->getContext(),
429
			'\GravityView_View::total_entries' => \GravityView_View::getInstance()->getTotalEntries(),
430
			'\GravityView_View::post_id' => \GravityView_View::getInstance()->getPostId(),
431
			'\GravityView_frontend::post_id' => \GravityView_frontend::getInstance()->getPostId(),
432
			'\GravityView_frontend::context_view_id' => \GravityView_frontend::getInstance()->get_context_view_id(),
433
			'\GravityView_frontend::is_gravityview_post_type' => \GravityView_frontend::getInstance()->isGravityviewPostType(),
434 22
			'\GravityView_frontend::post_has_shortcode' => \GravityView_frontend::getInstance()->isPostHasShortcode(),
435 22
			'\GravityView_frontend::gv_output_data' => \GravityView_frontend::getInstance()->getGvOutputData(),
436
			'\GravityView_View::paging' => \GravityView_View::getInstance()->getPaging(),
437
			'\GravityView_View::sorting' => \GravityView_View::getInstance()->getSorting(),
438 22
			'\GravityView_frontend::is_search' => \GravityView_frontend::getInstance()->isSearch(),
439 22
			'\GravityView_frontend::single_entry' => \GravityView_frontend::getInstance()->getSingleEntry(),
440 22
			'\GravityView_frontend::entry' => \GravityView_frontend::getInstance()->getEntry(),
441 22
			'\GravityView_View::_current_entry' => \GravityView_View::getInstance()->getCurrentEntry(),
442 22
			'\GravityView_View::fields' => \GravityView_View::getInstance()->getFields(),
443 22
			'wp_actions[loop_start]' => empty( $wp_actions['loop_start'] ) ? 0 : $wp_actions['loop_start'],
444 22
			'wp_query::in_the_loop' => $wp_query->in_the_loop,
445 22
		);
446 22
	}
447 22
448 22
	/**
449 22
	 * Unserializes a saved configuration. Modifies the global state.
450 22
	 *
451 22
	 * @param array $data Saved configuration from self::freeze()
452 22
	 */
453 22
	public static function thaw( $data ) {
454 22
		foreach ( (array)$data as $key => $value ) {
0 ignored issues
show
introduced by
No space after closing casting parenthesis is prohibited
Loading history...
455 22
			switch ( $key ):
456 22
				case '\GravityView_View::atts':
457 22
					\GravityView_View::getInstance()->setAtts( $value );
458 22
					break;
459 22
				case '\GravityView_View::view_id':
460 22
					\GravityView_View::getInstance()->setViewId( $value );
461 22
					break;
462
				case '\GravityView_View::back_link_label':
463
					\GravityView_View::getInstance()->setBackLinkLabel( $value );
464
					break;
465
				case '\GravityView_View_Data::views':
466
					\GravityView_View_Data::getInstance()->views = $value;
467
					break;
468
				case '\GravityView_View::entries':
469
					\GravityView_View::getInstance()->setEntries( $value );
470 22
					break;
471 22
				case '\GravityView_View::form':
472 22
					\GravityView_View::getInstance()->setForm( $value );
473 22
					break;
474 22
				case '\GravityView_View::form_id':
475 22
					\GravityView_View::getInstance()->setFormId( $value );
476 22
					break;
477 22
				case '\GravityView_View::context':
478 22
					\GravityView_View::getInstance()->setContext( $value );
479 22
					break;
480 22
				case '\GravityView_View::total_entries':
481 22
					\GravityView_View::getInstance()->setTotalEntries( $value );
482 22
					break;
483 22
				case '\GravityView_View::post_id':
484 22
					\GravityView_View::getInstance()->setPostId( $value );
485 22
					break;
486 22
				case '\GravityView_frontend::post_id':
487 22
					\GravityView_frontend::getInstance()->setPostId( $value );
488 22
					break;
489 22
				case '\GravityView_frontend::context_view_id':
490 22
					$frontend = \GravityView_frontend::getInstance();
491 22
					$frontend->context_view_id = $value;
492 22
					break;
493 22
				case '\GravityView_frontend::is_gravityview_post_type':
494 22
					\GravityView_frontend::getInstance()->setIsGravityviewPostType( $value );
495 22
					break;
496 22
				case '\GravityView_frontend::post_has_shortcode':
497 22
					\GravityView_frontend::getInstance()->setPostHasShortcode( $value );
498 22
					break;
499 22
				case '\GravityView_frontend::gv_output_data':
500 22
					\GravityView_frontend::getInstance()->setGvOutputData( $value );
501 22
					break;
502 22
				case '\GravityView_View::paging':
503 22
					\GravityView_View::getInstance()->setPaging( $value );
504 22
					break;
505 22
				case '\GravityView_View::sorting':
506 22
					\GravityView_View::getInstance()->setSorting( $value );
507 22
					break;
508 22
				case '\GravityView_frontend::is_search':
509 22
					\GravityView_frontend::getInstance()->setIsSearch( $value );
510 22
					break;
511 22
				case '\GravityView_frontend::single_entry':
512 22
					\GravityView_frontend::getInstance()->setSingleEntry( $value );
513 22
					break;
514 22
				case '\GravityView_frontend::entry':
515 22
					\GravityView_frontend::getInstance()->setEntry( $value );
516 22
					break;
517 22
				case '\GravityView_View::_current_entry':
518 22
					\GravityView_View::getInstance()->setCurrentEntry( $value );
519 22
					break;
520 22
				case '\GravityView_View::fields':
521 22
					\GravityView_View::getInstance()->setFields( $value );
522 22
					break;
523 22
				case 'wp_actions[loop_start]':
524 22
					global $wp_actions;
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...
525 22
					$wp_actions['loop_start'] = $value;
526 22
					break;
527 22
				case 'wp_query::in_the_loop':
528 22
					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...
529 22
					$wp_query->in_the_loop = $value;
530 22
					break;
531 22
			endswitch;
532 22
		}
533 22
	}
534 22
535 22
	/**
536 22
	 * Hydrates the legacy context globals as needed.
537 22
	 *
538 22
	 * @see self::push() for format.
539 22
	 *
540 22
	 * @return void
541 22
	 */
542 22
	public static function load( $configuration ) {
543 22
		foreach ( (array)$configuration as $key => $value ) {
0 ignored issues
show
introduced by
No space after closing casting parenthesis is prohibited
Loading history...
544 22
			switch ( $key ):
545 22
				case 'view':
546 22
					$views = new \GV\View_Collection();
547 22
					$views->add( $value );
548
549
					self::thaw( array(
550 22
						'\GravityView_View::atts' => $value->settings->as_atts(),
551
						'\GravityView_View::view_id' => $value->ID,
552
						'\GravityView_View::back_link_label' => $value->settings->get( 'back_link_label', null ),
553
						'\GravityView_View::form' => $value->form ? $value->form->form : null,
554
						'\GravityView_View::form_id' => $value->form ? $value->form->ID : null,
555
556
						'\GravityView_View_Data::views' => $views,
557
						'\GravityView_frontend::gv_output_data' => \GravityView_View_Data::getInstance(),
558
						'\GravityView_frontend::context_view_id' => $value->ID,
559 22
					) );
560 22
					break;
561 22
				case 'post':
562 22
					$has_shortcode = false;
563 22
					foreach ( \GV\Shortcode::parse( $value->post_content ) as $shortcode ) {
564 22
						if ( $shortcode->name == 'gravityview' ) {
0 ignored issues
show
introduced by
Found "== '". Use Yoda Condition checks, you must
Loading history...
565
							$has_shortcode = true;
566 22
							break;
567 22
						}
568 22
					}
569 22
					self::thaw( array(
570 22
						'\GravityView_View::post_id' => $value->ID,
571 22
						'\GravityView_frontend::post_id' => $value->ID,
572
						'\GravityView_frontend::is_gravityview_post_type' => $value->post_type == 'gravityview',
573 22
						'\GravityView_frontend::post_has_shortcode' => $has_shortcode,
574 22
					) );
575 22
					break;
576
				case 'views':
577 22
					self::thaw( array(
578 13
						'\GravityView_View_Data::views' => $value,
579 1
						'\GravityView_frontend::gv_output_data' => \GravityView_View_Data::getInstance(),
580 1
					) );
581
					break;
582
				case 'entries':
583
					self::thaw( array(
584
						'\GravityView_View::entries' => array_map( function( $e ) { return $e->as_entry(); }, $value->all() ),
585
						'\GravityView_View::total_entries' => $value->total(),
586 1
					) );
587 1
					break;
588 1
				case 'entry':
589 1
					self::thaw( array(
590 1
						'\GravityView_frontend::single_entry' => $value->ID,
591
						'\GravityView_frontend::entry' => $value->ID,
592 1
						'\GravityView_View::_current_entry' => $value->as_entry(),
593 13
					) );
594
					break;
595
				case 'fields':
596
					self::thaw( array(
597
						'\GravityView_View::fields' => $value->as_configuration(),
598
					) );
599 13
					break;
600 13
				case 'request':
601
					self::thaw( array(
602 13
						'\GravityView_View::context' => (
0 ignored issues
show
introduced by
Each line in an array declaration must end in a comma
Loading history...
603
							$value->is_entry() ? 'single' :
604 13
								( $value->is_edit_entry() ? 'edit' :
605 13
									( $value->is_view() ? 'directory': null )
606 1
								)
607 1
						),
608 1
						'\GravityView_frontend::is_search' => $value->is_search(),
609 1
					) );
610
611 1
					if ( ! $value->is_entry() ) {
612 13
						self::thaw( array(
613 3
							'\GravityView_frontend::single_entry' => 0,
614 3
							'\GravityView_frontend::entry' => 0
0 ignored issues
show
introduced by
Each line in an array declaration must end in a comma
Loading history...
615
						) );
616 3
					}
617 12
					break;
618 12
				case 'paging':
619 12
					self::thaw( array(
620 12
						'\GravityView_View::paging' => $value,
621 11
					) );
622 11
					break;
623
				case 'sorting':
624
					self::thaw( array(
625 12
						'\GravityView_View::sorting' => $value,
626
					) );
627
					break;
628 12
				case 'in_the_loop':
629 11
					self::thaw( array(
630 11
						'wp_query::in_the_loop' => $value,
631
						'wp_actions[loop_start]' => $value ? 1 : 0,
632
					) );
633
					break;
634 12
			endswitch;
635 12
		}
636 12
637 12
		global $gravityview_view;
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...
638
		$gravityview_view = \GravityView_View::getInstance();
639 12
	}
640 12
641 12
	/**
642 12
	 * Resets the global state completely.
643
	 *
644 12
	 * Use with utmost care, as filter and action callbacks
645 2
	 *  may be added again.
646 2
	 *
647 2
	 * Does not touch the context stack.
648 2
	 *
649
	 * @return void
650 22
	 */
651
	public static function reset() {
652
		\GravityView_View::$instance = null;
0 ignored issues
show
Bug introduced by
The property instance cannot be accessed from this context as it is declared private in class GravityView_View.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
653
		\GravityView_frontend::$instance = null;
0 ignored issues
show
Bug introduced by
The property instance cannot be accessed from this context as it is declared private in class GravityView_frontend.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
654 22
		\GravityView_View_Data::$instance = null;
0 ignored issues
show
Bug introduced by
The property instance cannot be accessed from this context as it is declared private in class GravityView_View_Data.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
655 22
656 22
		global $wp_query, $wp_actions;
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...
657
658
		$wp_query->in_the_loop = false;
659
		$wp_actions['loop_start'] = 0;
660
	}
661
}
662
663
664
/** Add some global fix for field capability discrepancies. */
665
add_filter( 'gravityview/configuration/fields', function( $fields ) {
666
	if ( empty( $fields  ) ) {
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces before closing bracket; 2 found
Loading history...
667
		return $fields;
668 61
	}
669 61
670 61
	/**
671 61
	 * Each view field is saved in a weird capability state by default.
672
	 *
673 61
	 * With loggedin set to false, but a capability of 'read' it introduces
674
	 *  some logical issues and is not robust. Fix this behavior throughout
675 61
	 *  core by making sure capability is '' if log in is not required.
676 61
	 *
677 61
	 * Perhaps in the UI a fix would be to unite the two fields (as our new
678
	 *  \GV\Field class already does) into one dropdown:
679
	 *
680
	 * Anyone, Logged In Only, ... etc. etc.
681
	 *
682
	 * The two "settings" should be as tightly coupled as possible to avoid
683 13
	 *  split logic scenarios. Uniting them into one field is the way to go.
684
	 */
685
686
	foreach ( $fields as $position => &$_fields ) {
687
688
		if ( empty( $_fields ) || ! is_array( $_fields ) ) {
689
			continue;
690
		}
691
692
		foreach ( $_fields as $uid => &$_field ) {
693
			if ( ! isset( $_field['only_loggedin'] ) ) {
694
				continue;
695
			}
696
			/** If we do not require login, we don't require a cap. */
697
			$_field['only_loggedin'] != '1' && ( $_field['only_loggedin_cap'] = '' );
698
		}
699
	}
700
	return $fields;
701
} );
702
703 13
704
/** Add a future fix to make sure field configurations include the form ID. */
705 13
add_filter( 'gravityview/view/configuration/fields', function( $fields, $view ) {
706
	if ( ! $view || empty( $fields ) ) {
707
		return $fields;
708
	}
709 13
710 13
	if ( ! $view->form || ! $view->form->ID ) {
711 10
		return $fields;
712
	}
713
714 13
	/**
715
	 * In order to instantiate the correct \GV\Field implementation
716
	 *  we need to provide a form_id inside the configuration.
717 13
	 *
718
	 * @todo Make sure this actually happens in the admin side
719
	 *  when saving the views.
720
	 */
721
	foreach ( $fields as $position => &$_fields ) {
722
723 67
		if ( empty( $_fields ) || ! is_array( $_fields ) ) {
724
			continue;
725
		}
726
727 67
		foreach ( $_fields as $uid => &$_field ) {
728
			if ( ! empty( $_field['id'] ) && is_numeric( $_field['id'] ) && empty( $_field['form_id'] ) ) {
729
				$_field['form_id'] = $view->form->ID;
730
			}
731
		}
732
	}
733
734
	return $fields;
735
}, 10, 2 );
736
737
738 67
/** Make sure the non-configured notice is not output twice. */
739
add_action( 'gravityview/template/after', function( $gravityview = null ) {
0 ignored issues
show
Unused Code introduced by
The parameter $gravityview 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...
740 67
	if ( class_exists( '\GravityView_frontend' ) ) {
741
		global $wp_filter;
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...
742
743
		if ( empty( $wp_filter['gravityview_after'] ) ) {
744 67
			return;
745 67
		}
746 67
747
		/** WordPress 4.6 and lower compatibility, when WP_Hook classes were still absent. */
748
		if ( is_array( $wp_filter['gravityview_after'] ) ) {
749
			if ( ! empty( $wp_filter['gravityview_after'][10] ) ) {
750
				foreach ( $wp_filter['gravityview_after'][10] as $function_key => $callback ) {
751 67
					if ( strpos( $function_key, 'context_not_configured_warning' ) ) {
752
						unset( $wp_filter['gravityview_after'][10][ $function_key ] );
753
					}
754
				}
755
			}
756
			return;
757 19
		}
758 19
759
		foreach ( $wp_filter['gravityview_after']->callbacks[10] as $function_key => $callback ) {
760 19
			if ( strpos( $function_key, 'context_not_configured_warning' ) ) {
761
				unset( $wp_filter['gravityview_after']->callbacks[10][ $function_key ] );
762
			}
763
		}
764
	}
765
} );
766