Completed
Push — develop ( d6e54c...488d60 )
by Zack
17:10
created

Legacy_Context::push()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 4
ccs 0
cts 0
cp 0
crap 2
rs 10
c 0
b 0
f 0
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 678.

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 1
	if ( is_array( $view_id ) ) {
18 1
		foreach ( $view_id as $id ) {
19 1
			call_user_func( __FUNCTION__, $id, $atts, $_this );
20
		}
21
22 1
		if ( ! $_this->views->count() ) {
23 1
			return array();
24
		}
25
26 1
		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 1
	if ( $view = $_this->views->get( $view_id ) ) {
34 1
		do_action( 'gravityview_log_debug', sprintf( 'GravityView_View_Data[add_view] Returning; View #%s already exists.', $view_id ) );
35 1
		return $view->as_data();
36
	}
37
38 1
	$view = \GV\View::by_id( $view_id );
39 1
	if ( ! $view ) {
40 1
		do_action( 'gravityview_log_debug', sprintf( 'GravityView_View_Data[add_view] Returning; View #%s does not exist.', $view_id ) );
41 1
		return false;
42
	}
43
44
	/** Doesn't have a connected form. */
45 1
	if ( ! $view->form ) {
46 1
		do_action( 'gravityview_log_debug', sprintf( 'GravityView_View_Data[add_view] Returning; Post ID #%s does not have a connected form.', $view_id ) );
47 1
		return false;
48
	}
49
50
	/** Update the settings */
51 1
	if ( is_array( $atts ) ) {
52 1
		$view->settings->update( $atts );
53
	}
54
55 1
	$_this->views->add( $view );
56
57 1
	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 = $form->entries
0 ignored issues
show
Documentation introduced by
The property entries does not exist on object<GV\GF_Form>. 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...
99 1
			->filter( \GV\GF_Entry_Filter::from_search_criteria( $criteria['search_criteria'] ) )
100 1
			->offset( $args['offset'] )
101 1
			->limit( $criteria['paging']['page_size'] );
102
103 1
		if ( $criteria['paging']['page_size'] ) {
104 1
			$entries = $entries->page( ( ( $criteria['paging']['offset'] - $args['offset'] ) / $criteria['paging']['page_size'] ) + 1 );
105
		}
106
107 1
		if ( ! empty( $criteria['sorting'] ) ) {
108 1
			$field = new \GV\Field();
109 1
			$field->ID = $criteria['sorting']['key'];
110 1
			switch( strtolower( $criteria['sorting']['direction'] ) ) {
111 1
				case 'asc':
112
					$direction = \GV\Entry_Sort::ASC;
113
					break;
114 1
				case 'rand':
115
					$direction = \GV\Entry_Sort::RAND;
116
					break;
117
				default:
118 1
				case 'desc':
0 ignored issues
show
Unused Code introduced by
case 'desc': $direct..._Sort::DESC; break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
119 1
					$direction = \GV\Entry_Sort::DESC;
120 1
					break;
121
			}
122
123 1
			$mode = $criteria['sorting']['is_numeric'] ? \GV\Entry_Sort::NUMERIC : \GV\Entry_Sort::ALPHA;
124 1
			$entries = $entries->sort( new \GV\Entry_Sort( $field, $direction, $mode ) );
125
		}
126
127
		/** Set paging, count and unwrap the entries. */
128
		$paging = array(
129 1
			'offset' => ( $entries->current_page - 1 ) * $entries->limit,
130 1
			'page_size' => $entries->limit,
131
		);
132 1
		$count = $entries->total();
133
		$entries = array_map( function( $e ) { return $e->as_entry(); }, $entries->all() );
134
	}
135
136
	/** Just one more filter, for compatibility's sake! */
137
138
	/**
139
	 * @deprecated
140
	 * Do not use this filter anymore.
141
	 */
142 1
	$entries = apply_filters_ref_array( 'gravityview_entries', array( $entries, $criteria, $parameters, &$count ) );
143
144 1
	return array( $entries, $paging, $count );
145
}
146
147
/**
148
 * The old function does a bit too much, not only does it retrieve
149 3
 *  the value for a field, but it also renders some output. We are
150
 *  stubbing the plain value part of it, the rendering will follow once
151
 *  our field renderers are ready.
152
 *
153
 * @see \GravityView_API::field_value
154
 * @deprecated Use \GV\Field_Template::render()
155
 * @internal
156
 * @since 2.0
157
 *
158
 * @return null|string The value of a field in an entry.
159
 */
160
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...
161
	if ( empty( $entry['form_id'] ) || empty( $field_settings['id'] ) ) {
162
		gravityview()->log->error( 'No entry or field_settings[id] supplied', array( 'data' => array( func_get_args() ) ) );
163
		return null;
164
	}
165
166
	if ( ! empty( $entry['_multi'] ) && ! empty( $field_settings['form_id'] ) && ! empty( $entry['_multi'][ $field_settings['form_id'] ] ) ) {
167
		$entry = $entry['_multi'][ $field_settings['form_id'] ];
168
	}
169 3
170
	if ( empty( $entry['id'] ) || ! $entry = \GV\GF_Entry::by_id( $entry['id'] ) ) {
171 3
		gravityview()->log->error( 'Invalid \GV\GF_Entry supplied', array( 'data' => $entry ) );
172
		return null;
173
	}
174
175 3
	/**
176 3
	 * Determine the source backend.
177
	 *
178
	 * Fields with a numeric ID are Gravity Forms ones.
179
	 */
180 3
	$source = is_numeric( $field_settings['id'] ) ? \GV\Source::BACKEND_GRAVITYFORMS : \GV\Source::BACKEND_INTERNAL;;
181
182
	/** Initialize the future field. */
183 3
	switch ( $source ):
184
		/** The Gravity Forms backend. */
185
		case \GV\Source::BACKEND_GRAVITYFORMS:
186
			if ( ! $form = \GV\GF_Form::by_id( $entry['form_id'] ) ) {
187
				gravityview()->log->error( 'No form Gravity Form found for entry', array( 'data' => $entry ) );
188
				return null;
189
			}
190
191
			if ( ! $field = $form::get_field( $form, $field_settings['id'] ) ) {
192
				return null;
193
			}
194
195
			break;
196
197
		/** Our internal backend. */
198
		case \GV\Source::BACKEND_INTERNAL:
199
			if ( ! $field = \GV\Internal_Source::get_field( $field_settings['id'] ) ) {
200
				return null;
201
			}
202
203
			break;
204
205
		/** An unidentified backend. */
206
		default:
207
			gravityview()->log->error( 'Could not determine source for entry', array( 'data' => array( func_get_args() ) ) );
208
			return null;
209
	endswitch;
210
211
	/** Add the field settings. */
212
	$field->update_configuration( $field_settings );
213
214
	$renderer = new \GV\Field_Renderer();
215
	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...
216
}
217
218
/**
219
 * Mock out the \GravityView_API::field_label method
220
 *
221
 * Uses the new \GV\Field::get_label methods
222
 *
223
 * @see \GravityView_API::field_label
224
 * @internal
225
 * @since 2.0
226
 *
227
 * @return string The label of a field in an entry.
228
 */
229
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...
230
231
	/** A bail condition. */
232
	$bail = function( $label, $field_settings, $entry, $force_show_label, $form ) {
233
		if ( ! empty( $field_settings['show_label'] ) || $force_show_label ) {
234
235
			$label = isset( $field_settings['label'] ) ? $field_settings['label'] : '';
236
237
			// Use Gravity Forms label by default, but if a custom label is defined in GV, use it.
238
			if ( ! empty( $field_settings['custom_label'] ) ) {
239
				$label = \GravityView_API::replace_variables( $field_settings['custom_label'], $form, $entry );
240
			}
241
242
			/**
243
			 * @filter `gravityview_render_after_label` Append content to a field label
244
			 * @param[in,out] string $appended_content Content you can add after a label. Empty by default.
245
			 * @param[in] array $field GravityView field array
246
			 */
247
			$label .= apply_filters( 'gravityview_render_after_label', '', $field_settings );
248
		}
249
250
		/**
251
		 * @filter `gravityview/template/field_label` Modify field label output
252
		 * @since 1.7
253
		 * @param[in,out] string $label Field label HTML
254
		 * @param[in] array $field GravityView field array
255
		 * @param[in] array $form Gravity Forms form array
256
		 * @param[in] array $entry Gravity Forms entry array
257
		 */
258
		$label = apply_filters( 'gravityview/template/field_label', $label, $field_settings, $form, $entry );
259
260
		return $label;
261
	};
262
263
	$label = '';
264
265
	if ( ! empty( $entry['_multi'] ) && ! empty( $field_settings['form_id'] ) && ! empty( $entry['_multi'][ $field_settings['form_id'] ] ) ) {
266
		$entry = $entry['_multi'][ $field_settings['form_id'] ];
267
		if ( $_form = \GV\GF_Form::by_id( $field_settings['form_id'] ) ) {
268
			$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...
269
		}
270
	}
271
272
	if ( empty( $entry['form_id'] ) || empty( $field_settings['id'] ) ) {
273
		gravityview()->log->error( 'No entry or field_settings[id] supplied', array( 'data' => array( func_get_args() ) ) );
274
		return $bail( $label, $field_settings, $entry, $force_show_label, $form );
275
	}
276
277
	if ( empty( $entry['id'] ) || ! $gv_entry = \GV\GF_Entry::by_id( $entry['id'] ) ) {
278
		gravityview()->log->error( 'Invalid \GV\GF_Entry supplied', array( 'data' => $entry ) );
279
		return $bail( $label, $field_settings, $entry, $force_show_label, $form );
280
	}
281
282
	$entry = $gv_entry;
283
284
	/**
285
	 * Determine the source backend.
286
	 *
287
	 * Fields with a numeric ID are Gravity Forms ones.
288
	 */
289
	$source = is_numeric( $field_settings['id'] ) ? \GV\Source::BACKEND_GRAVITYFORMS : \GV\Source::BACKEND_INTERNAL;
290
291
	/** Initialize the future field. */
292
	switch ( $source ):
293
		/** The Gravity Forms backend. */
294
		case \GV\Source::BACKEND_GRAVITYFORMS:
295
			if ( ! $gf_form = \GV\GF_Form::by_id( $entry['form_id'] ) ) {
296
				gravityview()->log->error( 'No form Gravity Form found for entry', array( 'data' => $entry ) );
297
				return $bail( $label, $field_settings, $entry->as_entry(), $force_show_label, $form );
298
			}
299
300
			if ( ! $field = $gf_form::get_field( $gf_form, $field_settings['id'] ) ) {
301
				gravityview()->log->error( 'No field found for specified form and field ID #{field_id}', array( 'field_id' => $field_settings['id'], 'data' => $form ) );
302
				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...
303
			}
304
			if ( empty( $field_settings['show_label'] ) ) {
305
				/** The label never wins... */
306
				$field_settings['label'] = '';
307
			}
308
309
			break;
310
311
		/** Our internal backend. */
312
		case \GV\Source::BACKEND_INTERNAL:
313
			if ( ! $field = \GV\Internal_Source::get_field( $field_settings['id'] ) ) {
314
				return $bail( $label, $field_settings, $entry->as_entry(), $force_show_label, $form );
315
			}
316
			break;
317
318
		/** An unidentified backend. */
319
		default:
320
			gravityview()->log->error( 'Could not determine source for entry. Using empty field.', array( 'data' => array( func_get_args() ) ) );
321
			$field = new \GV\Field();
322
			break;
323
	endswitch;
324
325
	/** Add the field settings. */
326
	$field->update_configuration( $field_settings );
327
328
	if ( ! empty( $field->show_label ) || $force_show_label ) {
329
330
		$label = $field->get_label( null, isset( $gf_form ) ? $gf_form : null, $entry );
331
332
		/**
333
		 * @filter `gravityview_render_after_label` Append content to a field label
334
		 * @param[in,out] string $appended_content Content you can add after a label. Empty by default.
335
		 * @param[in] array $field GravityView field array
336
		 */
337
		$label .= apply_filters( 'gravityview_render_after_label', '', $field->as_configuration() );
338
339
	}
340
341
	/**
342
	 * @filter `gravityview/template/field_label` Modify field label output
343
	 * @since 1.7
344
	 * @param[in,out] string $label Field label HTML
345
	 * @param[in] array $field GravityView field array
346
	 * @param[in] array $form Gravity Forms form array
347
	 * @param[in] array $entry Gravity Forms entry array
348
	 */
349
	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...
350
}
351
352
353
/**
354
 * A manager of legacy global states and contexts.
355
 *
356
 * Handles mocking of:
357
 * - \GravityView_View_Data
358
 * - \GravityView_View
359
 * - \GravityView_frontend
360
 *
361
 * Allows us to set a specific state globally using the old
362
 *  containers, then reset it. Useful for legacy code that keeps
363
 *  on depending on these variables.
364
 *
365
 * Some examples right now include template files, utility functions,
366
 *  some actions and filters that expect the old contexts to be set.
367
 */
368
final class Legacy_Context {
369
	private static $stack = array();
370
371
	/**
372
	 * Set the state depending on the provided configuration.
373
	 *
374
	 * Saves current global state and context.
375
	 *
376
	 * Configuration keys:
377
	 *
378
	 * - \GV\View	view:		sets \GravityView_View::atts, \GravityView_View::view_id,
379
	 *								 \GravityView_View::back_link_label
380
	 *								 \GravityView_frontend::context_view_id,
381
	 *								 \GravityView_View::form, \GravityView_View::form_id
382
	 * - \GV\Field	field:		sets \GravityView_View::_current_field, \GravityView_View::field_data,
383
	 * - \GV\Entry	entry:		sets \GravityView_View::_current_entry, \GravityView_frontend::single_entry,
384
	 *								 \GravityView_frontend::entry
385
	 * - \WP_Post	post:		sets \GravityView_View::post_id, \GravityView_frontend::post_id,
386
	 *								 \GravityView_frontend::is_gravityview_post_type,
387
	 *								 \GravityView_frontend::post_has_shortcode
388
	 * - array		paging:		sets \GravityView_View::paging
389
	 * - array		sorting:	sets \GravityView_View::sorting
390
	 * - array		template:	sets \GravityView_View::template_part_slug, \GravityView_View::template_part_name
391
	 *
392
	 * - boolean	in_the_loop sets $wp_actions['loop_start'] and $wp_query::in_the_loop
393
	 *
394
	 * also:
395
	 *
396
	 * - \GV\Request	request:	sets \GravityView_frontend::is_search, \GravityView_frontend::single_entry,
397
	 *									 \GravityView_View::context, \GravityView_frontend::entry
398
	 *
399
	 * - \GV\View_Collection	views:		sets \GravityView_View_Data::views
400
	 * - \GV\Field_Collection	fields:		sets \GravityView_View::fields
401
	 * - \GV\Entry_Collection	entries:	sets \GravityView_View::entries, \GravityView_View::total_entries
402
	 *
403
	 * and automagically:
404
	 *
405
	 * - \GravityView_View		data:		sets \GravityView_frontend::gv_output_data
406
	 *
407
	 * @param array $configuration The configuration.
408
	 *
409
	 * @return void
410
	 */
411
	public static function push( $configuration ) {
412
		array_push( self::$stack, self::freeze() );
413
		self::load( $configuration );
414
	}
415
416
	/**
417
	 * Restores last saved state and context.
418
	 *
419
	 * @return void
420
	 */
421
	public static function pop() {
422
		self::thaw( array_pop( self::$stack ) );
423
	}
424
425
	/**
426
	 * Serializes the current configuration as needed.
427
	 *
428
	 * @return array The configuration.
429
	 */
430
	public static function freeze() {
431
		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...
432
433
		return array(
434
			'\GravityView_View::atts' => \GravityView_View::getInstance()->getAtts(),
435
			'\GravityView_View::view_id' => \GravityView_View::getInstance()->getViewId(),
436
			'\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...
437
			'\GravityView_View_Data::views' => \GravityView_View_Data::getInstance()->views,
438
			'\GravityView_View::entries' => \GravityView_View::getInstance()->getEntries(),
439
			'\GravityView_View::form' => \GravityView_View::getInstance()->getForm(),
440
			'\GravityView_View::form_id' => \GravityView_View::getInstance()->getFormId(),
441
			'\GravityView_View::context' => \GravityView_View::getInstance()->getContext(),
442
			'\GravityView_View::total_entries' => \GravityView_View::getInstance()->getTotalEntries(),
443
			'\GravityView_View::post_id' => \GravityView_View::getInstance()->getPostId(),
444
			'\GravityView_frontend::post_id' => \GravityView_frontend::getInstance()->getPostId(),
445
			'\GravityView_frontend::context_view_id' => \GravityView_frontend::getInstance()->get_context_view_id(),
446
			'\GravityView_frontend::is_gravityview_post_type' => \GravityView_frontend::getInstance()->isGravityviewPostType(),
447
			'\GravityView_frontend::post_has_shortcode' => \GravityView_frontend::getInstance()->isPostHasShortcode(),
448
			'\GravityView_frontend::gv_output_data' => \GravityView_frontend::getInstance()->getGvOutputData(),
449
			'\GravityView_View::paging' => \GravityView_View::getInstance()->getPaging(),
450
			'\GravityView_View::sorting' => \GravityView_View::getInstance()->getSorting(),
451
			'\GravityView_frontend::is_search' => \GravityView_frontend::getInstance()->isSearch(),
452
			'\GravityView_frontend::single_entry' => \GravityView_frontend::getInstance()->getSingleEntry(),
453
			'\GravityView_frontend::entry' => \GravityView_frontend::getInstance()->getEntry(),
454
			'\GravityView_View::_current_entry' => \GravityView_View::getInstance()->getCurrentEntry(),
455
			'\GravityView_View::fields' => \GravityView_View::getInstance()->getFields(),
456
			'wp_actions[loop_start]' => empty( $wp_actions['loop_start'] ) ? 0 : $wp_actions['loop_start'],
457
			'wp_query::in_the_loop' => $wp_query->in_the_loop,
458
		);
459
	}
460
461
	/**
462
	 * Unserializes a saved configuration. Modifies the global state.
463
	 *
464
	 * @param array $data Saved configuration from self::freeze()
465
	 */
466
	public static function thaw( $data ) {
467
		foreach ( (array)$data as $key => $value ) {
0 ignored issues
show
introduced by
No space after closing casting parenthesis is prohibited
Loading history...
468
			switch ( $key ):
469
				case '\GravityView_View::atts':
470
					\GravityView_View::getInstance()->setAtts( $value );
471
					break;
472
				case '\GravityView_View::view_id':
473
					\GravityView_View::getInstance()->setViewId( $value );
474
					break;
475
				case '\GravityView_View::back_link_label':
476
					\GravityView_View::getInstance()->setBackLinkLabel( $value );
477
					break;
478
				case '\GravityView_View_Data::views':
479
					\GravityView_View_Data::getInstance()->views = $value;
480
					break;
481
				case '\GravityView_View::entries':
482
					\GravityView_View::getInstance()->setEntries( $value );
483
					break;
484
				case '\GravityView_View::form':
485
					\GravityView_View::getInstance()->setForm( $value );
486
					break;
487
				case '\GravityView_View::form_id':
488
					\GravityView_View::getInstance()->setFormId( $value );
489
					break;
490
				case '\GravityView_View::context':
491
					\GravityView_View::getInstance()->setContext( $value );
492
					break;
493
				case '\GravityView_View::total_entries':
494
					\GravityView_View::getInstance()->setTotalEntries( $value );
495
					break;
496
				case '\GravityView_View::post_id':
497
					\GravityView_View::getInstance()->setPostId( $value );
498
					break;
499
				case '\GravityView_frontend::post_id':
500
					\GravityView_frontend::getInstance()->setPostId( $value );
501
					break;
502
				case '\GravityView_frontend::context_view_id':
503
					$frontend = \GravityView_frontend::getInstance();
504
					$frontend->context_view_id = $value;
505
					break;
506
				case '\GravityView_frontend::is_gravityview_post_type':
507
					\GravityView_frontend::getInstance()->setIsGravityviewPostType( $value );
508
					break;
509
				case '\GravityView_frontend::post_has_shortcode':
510
					\GravityView_frontend::getInstance()->setPostHasShortcode( $value );
511
					break;
512
				case '\GravityView_frontend::gv_output_data':
513
					\GravityView_frontend::getInstance()->setGvOutputData( $value );
514
					break;
515
				case '\GravityView_View::paging':
516
					\GravityView_View::getInstance()->setPaging( $value );
517
					break;
518
				case '\GravityView_View::sorting':
519
					\GravityView_View::getInstance()->setSorting( $value );
520
					break;
521
				case '\GravityView_frontend::is_search':
522
					\GravityView_frontend::getInstance()->setIsSearch( $value );
523
					break;
524
				case '\GravityView_frontend::single_entry':
525
					\GravityView_frontend::getInstance()->setSingleEntry( $value );
526
					break;
527
				case '\GravityView_frontend::entry':
528
					\GravityView_frontend::getInstance()->setEntry( $value );
529
					break;
530
				case '\GravityView_View::_current_entry':
531
					\GravityView_View::getInstance()->setCurrentEntry( $value );
532
					break;
533
				case '\GravityView_View::fields':
534
					\GravityView_View::getInstance()->setFields( $value );
535
					break;
536
				case 'wp_actions[loop_start]':
537
					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...
538
					$wp_actions['loop_start'] = $value;
539
					break;
540
				case 'wp_query::in_the_loop':
541
					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...
542
					$wp_query->in_the_loop = $value;
543
					break;
544
			endswitch;
545
		}
546
	}
547
548
	/**
549
	 * Hydrates the legacy context globals as needed.
550
	 *
551
	 * @see self::push() for format.
552
	 *
553
	 * @return void
554
	 */
555
	public static function load( $configuration ) {
556
		foreach ( (array)$configuration as $key => $value ) {
0 ignored issues
show
introduced by
No space after closing casting parenthesis is prohibited
Loading history...
557
			switch ( $key ):
558
				case 'view':
559
					$views = new \GV\View_Collection();
560
					$views->add( $value );
561
562
					self::thaw( array(
563
						'\GravityView_View::atts' => $value->settings->as_atts(),
564
						'\GravityView_View::view_id' => $value->ID,
565
						'\GravityView_View::back_link_label' => $value->settings->get( 'back_link_label', null ),
566
						'\GravityView_View::form' => $value->form ? $value->form->form : null,
567
						'\GravityView_View::form_id' => $value->form ? $value->form->ID : null,
568
569
						'\GravityView_View_Data::views' => $views,
570
						'\GravityView_frontend::gv_output_data' => \GravityView_View_Data::getInstance(),
571
						'\GravityView_frontend::context_view_id' => $value->ID,
572
					) );
573
					break;
574
				case 'post':
575
					$has_shortcode = false;
576
					foreach ( \GV\Shortcode::parse( $value->post_content ) as $shortcode ) {
577
						if ( $shortcode->name == 'gravityview' ) {
0 ignored issues
show
introduced by
Found "== '". Use Yoda Condition checks, you must
Loading history...
578
							$has_shortcode = true;
579
							break;
580
						}
581
					}
582
					self::thaw( array(
583
						'\GravityView_View::post_id' => $value->ID,
584
						'\GravityView_frontend::post_id' => $value->ID,
585
						'\GravityView_frontend::is_gravityview_post_type' => $value->post_type == 'gravityview',
586
						'\GravityView_frontend::post_has_shortcode' => $has_shortcode,
587
					) );
588
					break;
589
				case 'views':
590
					self::thaw( array(
591
						'\GravityView_View_Data::views' => $value,
592
						'\GravityView_frontend::gv_output_data' => \GravityView_View_Data::getInstance(),
593
					) );
594
					break;
595
				case 'entries':
596
					self::thaw( array(
597
						'\GravityView_View::entries' => array_map( function( $e ) { return $e->as_entry(); }, $value->all() ),
598
						'\GravityView_View::total_entries' => $value->total(),
599
					) );
600
					break;
601
				case 'entry':
602
					self::thaw( array(
603
						'\GravityView_frontend::single_entry' => $value->ID,
604
						'\GravityView_frontend::entry' => $value->ID,
605
						'\GravityView_View::_current_entry' => $value->as_entry(),
606
					) );
607
					break;
608
				case 'fields':
609
					self::thaw( array(
610
						'\GravityView_View::fields' => $value->as_configuration(),
611
					) );
612
					break;
613
				case 'request':
614
					self::thaw( array(
615
						'\GravityView_View::context' => (
0 ignored issues
show
introduced by
Each line in an array declaration must end in a comma
Loading history...
616
							$value->is_entry() ? 'single' :
617
								( $value->is_edit_entry() ? 'edit' :
618
									( $value->is_view() ? 'directory': null )
619
								)
620
						),
621
						'\GravityView_frontend::is_search' => $value->is_search(),
622
					) );
623
624
					if ( ! $value->is_entry() ) {
625
						self::thaw( array(
626
							'\GravityView_frontend::single_entry' => 0,
627
							'\GravityView_frontend::entry' => 0
0 ignored issues
show
introduced by
Each line in an array declaration must end in a comma
Loading history...
628
						) );
629
					}
630
					break;
631
				case 'paging':
632
					self::thaw( array(
633
						'\GravityView_View::paging' => $value,
634
					) );
635
					break;
636
				case 'sorting':
637
					self::thaw( array(
638
						'\GravityView_View::sorting' => $value,
639
					) );
640
					break;
641
				case 'in_the_loop':
642
					self::thaw( array(
643
						'wp_query::in_the_loop' => $value,
644
						'wp_actions[loop_start]' => $value ? 1 : 0,
645
					) );
646
					break;
647
			endswitch;
648
		}
649
650
		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...
651
		$gravityview_view = \GravityView_View::getInstance();
652
	}
653
654
	/**
655
	 * Resets the global state completely.
656
	 *
657
	 * Use with utmost care, as filter and action callbacks
658
	 *  may be added again.
659
	 *
660
	 * Does not touch the context stack.
661
	 *
662
	 * @return void
663
	 */
664
	public static function reset() {
665
		\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...
666
		\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...
667
		\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...
668
669
		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...
670
671
		$wp_query->in_the_loop = false;
672
		$wp_actions['loop_start'] = 0;
673
	}
674
}
675
676
677
/** Add some global fix for field capability discrepancies. */
678
add_filter( 'gravityview/configuration/fields', function( $fields ) {
679
	if ( empty( $fields  ) ) {
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces before closing bracket; 2 found
Loading history...
680
		return $fields;
681
	}
682
683
	/**
684
	 * Each view field is saved in a weird capability state by default.
685
	 *
686
	 * With loggedin set to false, but a capability of 'read' it introduces
687
	 *  some logical issues and is not robust. Fix this behavior throughout
688
	 *  core by making sure capability is '' if log in is not required.
689
	 *
690
	 * Perhaps in the UI a fix would be to unite the two fields (as our new
691
	 *  \GV\Field class already does) into one dropdown:
692
	 *
693
	 * Anyone, Logged In Only, ... etc. etc.
694
	 *
695
	 * The two "settings" should be as tightly coupled as possible to avoid
696
	 *  split logic scenarios. Uniting them into one field is the way to go.
697
	 */
698
699
	foreach ( $fields as $position => &$_fields ) {
700
701
		if ( empty( $_fields ) || ! is_array( $_fields ) ) {
702
			continue;
703
		}
704
705
		foreach ( $_fields as $uid => &$_field ) {
706
			if ( ! isset( $_field['only_loggedin'] ) ) {
707
				continue;
708
			}
709
			/** If we do not require login, we don't require a cap. */
710
			$_field['only_loggedin'] != '1' && ( $_field['only_loggedin_cap'] = '' );
711
		}
712
	}
713
	return $fields;
714
} );
715
716
717
/** Add a future fix to make sure field configurations include the form ID. */
718
add_filter( 'gravityview/view/configuration/fields', function( $fields, $view ) {
719
	if ( ! $view || empty( $fields ) ) {
720
		return $fields;
721
	}
722
723
	if ( ! $view->form || ! $view->form->ID ) {
724
		return $fields;
725
	}
726
727
	/**
728
	 * In order to instantiate the correct \GV\Field implementation
729
	 *  we need to provide a form_id inside the configuration.
730
	 *
731
	 * @todo Make sure this actually happens in the admin side
732
	 *  when saving the views.
733
	 */
734
	foreach ( $fields as $position => &$_fields ) {
735
736
		if ( empty( $_fields ) || ! is_array( $_fields ) ) {
737
			continue;
738
		}
739
740
		foreach ( $_fields as $uid => &$_field ) {
741
			if ( ! empty( $_field['id'] ) && is_numeric( $_field['id'] ) && empty( $_field['form_id'] ) ) {
742
				$_field['form_id'] = $view->form->ID;
743
			}
744
		}
745
	}
746
747
	return $fields;
748
}, 10, 2 );
749
750
751
/** Make sure the non-configured notice is not output twice. */
752
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...
753
	if ( class_exists( '\GravityView_frontend' ) ) {
754
		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...
755
756
		if ( empty( $wp_filter['gravityview_after'] ) ) {
757
			return;
758
		}
759
760
		/** WordPress 4.6 and lower compatibility, when WP_Hook classes were still absent. */
761
		if ( is_array( $wp_filter['gravityview_after'] ) ) {
762
			if ( ! empty( $wp_filter['gravityview_after'][10] ) ) {
763
				foreach ( $wp_filter['gravityview_after'][10] as $function_key => $callback ) {
764
					if ( strpos( $function_key, 'context_not_configured_warning' ) ) {
765
						unset( $wp_filter['gravityview_after'][10][ $function_key ] );
766
					}
767
				}
768
			}
769
			return;
770
		}
771
772
		foreach ( $wp_filter['gravityview_after']->callbacks[10] as $function_key => $callback ) {
773
			if ( strpos( $function_key, 'context_not_configured_warning' ) ) {
774
				unset( $wp_filter['gravityview_after']->callbacks[10][ $function_key ] );
775
			}
776
		}
777
	}
778
} );
779