Completed
Pull Request — develop (#1194)
by Zack
06:38
created

add_id_specific_templates()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
nc 2
nop 3
dl 0
loc 21
ccs 9
cts 9
cp 1
crap 3
rs 9.584
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 23 and the first side effect is on line 6.

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;
3
4
/** If this file is called directly, abort. */
5
if ( ! defined( 'GRAVITYVIEW_DIR' ) ) {
6
	die();
7
}
8
9
/**
10
 * Load up the Gamajo Template Loader.
11
 *
12
 * @see https://github.com/GaryJones/Gamajo-Template-Loader
13
 */
14
if ( ! class_exists( '\GV\Gamajo_Template_Loader' ) ) {
15
	require gravityview()->plugin->dir( 'future/lib/class-gamajo-template-loader.php' );
16
}
17
18
/**
19
 * Loads legacy override templates from the theme.
20
 *
21
 * Makes sure they work by setting up context, etc.
22
 */
23
class Legacy_Override_Template extends \GV\Gamajo_Template_Loader {
24
	/**
25
	 * Prefix for filter names.
26
	 * @var string
27
	 */
28
	protected $filter_prefix = 'gravityview';
29
30
	/**
31
	 * Directory name where custom templates for this plugin should be found in the theme.
32
	 * @var string
33
	 */
34
	protected $theme_template_directory = 'gravityview';
35
36
	/**
37
	 * @var \GV\View The view we're working with.
38
	 */
39
	private $view;
40
41
	/**
42
	 * @var \GV\Entry The entry we're working with.
43
	 */
44
	private $entry;
45
46
	/**
47
	 * Catch deprecated template loads.
48
	 *
49
	 * @param \GV\View $view The View.
50
	 * @param \GV\Entry $entry The Entry.
51
	 * @param \GV\Field $field The Field.
52
	 * @param \GV\Request $request The request.
53
	 *
54
	 * @return void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
55
	 */
56 31
	public function __construct( \GV\View $view, \GV\Entry $entry = null, \GV\Field $field = null, \GV\Request $request = null ) {
0 ignored issues
show
Unused Code introduced by
The parameter $field 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...
Unused Code introduced by
The parameter $request 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...
57 31
		add_filter( $this->filter_prefix . '_get_template_part', array( $this, 'add_id_specific_templates' ), 10, 3 );
58
59 31
		$this->view = $view;
60 31
		$this->entry = $entry;
61
62 31
		$this->plugin_directory = gravityview()->plugin->dir();
63 31
		$this->plugin_template_directory = 'templates/deprecated/';
64 31
	}
65
66 6
	public function __destruct() {
67 6
		remove_filter( $this->filter_prefix . '_get_template_part', array( $this, 'add_id_specific_templates' ) );
68 6
	}
69
70
	/**
71
	 * @inheritdoc
72
	 * @see Gamajo_Template_Loader::locate_template()
73
	 * @return null|string NULL: Template not found; String: path to template
74
	 */
75 31
	public function locate_template( $template_names, $load = false, $require_once = false ) {
76 31
		return parent::locate_template( $template_names, false, false );
77
	}
78
79
	/**
80
	 * Enable overrides of GravityView templates on a granular basis
81
	 *
82
	 * The loading order is:
83
	 *
84
	 * - view-[View ID]-table-footer.php
85
	 * - form-[Form ID]-table-footer.php
86
	 * - page-[ID of post or page where view is embedded]-table-footer.php
87
	 * - table-footer.php
88
	 *
89
	 * @see  Gamajo_Template_Loader::get_template_file_names() Where the filter is
90
	 * @param array $templates Existing list of templates.
91
	 * @param string $slug      Name of the template base, example: `table`, `list`, `datatables`, `map`
92
	 * @param string $name      Name of the template part, example: `body`, `footer`, `head`, `single`
93
	 *
94
	 * @return array $templates Modified template array, merged with existing $templates values
95
	 */
96 31
	public function add_id_specific_templates( $templates, $slug, $name ) {
97
98 31
		$additional = array();
99
100
		// form-19-table-body.php
101 31
		$additional[] = sprintf( 'form-%d-%s-%s.php', $this->view->form ? $this->view->form->ID : 0, $slug, $name );
102
103
		// view-3-table-body.php
104 31
		$additional[] = sprintf( 'view-%d-%s-%s.php', $this->view->ID, $slug, $name );
0 ignored issues
show
Documentation introduced by
The property ID does not exist on object<GV\View>. Since you implemented __get, maybe consider adding a @property annotation.

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

<?php

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

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

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

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

}

If the property has read access only, you can use the @property-read annotation instead.

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

See also the PhpDoc documentation for @property.

Loading history...
105
106 31
		global $post;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
107 31
		if ( $post ) {
108
			// page-19-table-body.php
109 11
			$additional[] = sprintf( 'page-%d-%s-%s.php', $post->ID, $slug, $name );
110
		}
111
112
		// Combine with existing table-body.php and table.php
113 31
		$templates = array_merge( $additional, $templates );
114
115 31
		return $templates;
116
	}
117
118
	/**
119
	 * Setup legacy rendering.
120
	 *
121
	 * @param string $slug The slug.
122
	 *
123
	 * @return string The output.
124
	 */
125
	public function render( $slug ) {
126 2
		add_action( 'gravityview/template/after', $view_id_output = function( $context ) {
127
			printf( '<input type="hidden" class="gravityview-view-id" value="%d">', $context->view->ID );
128 2
		} );
129
130
		ob_start();
131
132
		$request = new Mock_Request();
133
		$request->returns['is_view'] = $this->view;
134
135
		/**
136
		 * You got one shot. One opportunity. To render all the widgets you have ever wanted.
137
		 *
138
		 * Since we're overriding the singleton we need to remove the widget actions since they can only
139
		 *  be called once in a request (did_action/do_action mutex).
140
		 *
141
		 * Oh, and Mom's spaghetti.
142
		 */
143
		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...
144
		foreach ( array( 'gravityview_before', 'gravityview_after' ) as $hook ) {
145
			/** WordPress 4.6 and lower compatibility, when WP_Hook classes were still absent. */
146
			if ( is_array( $wp_filter[ $hook ] ) ) {
147
				if ( ! empty( $wp_filter[ $hook ][10] ) ) {
148
					foreach ( $wp_filter[ $hook ][10] as $function_key => $callback ) {
149
						if ( strpos( $function_key, 'render_widget_hooks' ) ) {
150
							unset( $wp_filter[ $hook ][10][ $function_key ] );
151
						}
152
					}
153
				}
154
			} else {
155
				foreach ( $wp_filter[ $hook ]->callbacks[10] as $function_key => $callback ) {
156
					if ( strpos( $function_key, 'render_widget_hooks' ) ) {
157
						unset( $wp_filter[ $hook ]->callbacks[10][ $function_key ] );
158
					}
159
				}
160
			}
161
		}
162
		
163
		/**
164
		 * Single entry view.
165
		 */
166
		if ( $this->entry ) {
167
168
			$request->returns['is_entry'] = $this->entry;
169
170
			global $post;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
171
172
			$entries = new Entry_Collection();
173
			$entries->add( $this->entry );
174
175
			\GV\Mocks\Legacy_Context::push( array(
176
				'view' => $this->view,
177
				'entry' => $this->entry,
178
				'entries' => $entries,
179
				'request' => $request,
180
				'fields' => $this->view->fields->by_visible(),
181
				'in_the_loop' => true,
182
			) );
183
184
			\GravityView_View::getInstance()->setTemplatePartSlug( $slug );
185
			\GravityView_View::getInstance()->setTemplatePartName( 'single' );
186
187
			\GravityView_View::getInstance()->_include( $this->get_template_part( $slug, 'single' ) );
188
189
			Mocks\Legacy_Context::pop();
190
191
		/**
192
		 * Directory view.
193
		 */
194
		} else {
195
			$entries = $this->view->get_entries( $request );
196
197
			/**
198
			 * Remove multiple sorting before calling legacy filters.
199
			 * This allows us to fake it till we make it.
200
			 */
201
			$parameters = $view->settings->as_atts();
0 ignored issues
show
Bug introduced by
The variable $view does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
202
			if ( ! empty( $parameters['sort_field'] ) && is_array( $parameters['sort_field'] ) ) {
203
				$has_multisort = true;
204
				$parameters['sort_field'] = reset( $parameters['sort_field'] );
205
				if ( ! empty( $parameters['sort_direction'] ) && is_array( $parameters['sort_direction'] ) ) {
206
					$parameters['sort_direction'] = reset( $parameters['sort_direction'] );
207
				}
208
			}
209
210
			$parameters = \GravityView_frontend::get_view_entries_parameters( $parameters, $this->view->form->ID );
211
212
			global $post;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
213
214
			add_action( 'gravityview_before', array( \GravityView_View::getInstance(), 'render_widget_hooks' ) );
215
			add_action( 'gravityview_after', array( \GravityView_View::getInstance(), 'render_widget_hooks' ) );
216
217
			foreach ( array( 'header', 'body', 'footer' ) as $part ) {
218
				\GV\Mocks\Legacy_Context::push( array_merge( array(
219
					'view' => $this->view,
220
					'entries' => $entries,
221
					'request' => $request,
222
					'fields' => $this->view->fields->by_visible(),
223
					'in_the_loop' => true,
224
				), empty( $parameters ) ? array() : array(
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 20 spaces, but found 16.
Loading history...
225
					'paging' => $parameters['paging'],
226
					'sorting' => $parameters['sorting'],
227
				), $post ? array(
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 20 spaces, but found 16.
Loading history...
228
					'post' => $post,
229
				) : array() ) );
230
231
				\GravityView_View::getInstance()->setTemplatePartSlug( $slug );
232
233
				\GravityView_View::getInstance()->setTemplatePartName( $part );
234
235
				\GravityView_View::getInstance()->_include( $this->get_template_part( $slug, $part ) );
236
237
				Mocks\Legacy_Context::pop();
238
			}
239
		}
240
241
		remove_action( 'gravityview/template/after', $view_id_output );
242
243
		return ob_get_clean();
244
	}
245
}
246