Completed
Push — master ( 14e1a2...154914 )
by Zack
18:57 queued 01:08
created

Field::is_visible()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 9
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 1
nop 0
dl 0
loc 9
ccs 2
cts 2
cp 1
crap 2
rs 9.6666
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 14 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
 * The default GravityView Field class.
11
 *
12
 * Houses all base Field functionality.
13
 */
14
class Field {
15
16
	/**
17
	 * @var array The custom View configuration for this field.
18
	 *
19
	 * Everything else is in the properties.
20
	 */
21
	private $configuration = array();
22
23
	/**
24
	 * @var string The field position in the view.
25
	 * @api
26
	 * @since 2.0
27
	 */
28
	public $position = '';
29
30
	/**
31
	 * @var string UID for this field.
32
	 *
33
	 * A unique relation identifier between this field and a view.
34
	 *
35
	 * @api
36
	 * @since 2.0
37
	 */
38
	public $UID = '';
39
40
	/**
41
	 * @var string The form field ID for this field.
42
	 * @api
43
	 * @since 2.0
44
	 */
45
	public $ID = '';
46
47
	/**
48
	 * @var string The form label for this field.
49
	 * @api
50
	 * @since 2.0
51
	 */
52
	public $label = '';
53
54
	/**
55
	 * @var string The custom label for this field.
56
	 * @api
57
	 * @since 2.0
58
	 */
59
	public $custom_label = '';
60
61
	/**
62
	 * @var bool Whether to show the label or not for this field.
63
	 * @api
64
	 * @since 2.0
65
	 */
66
	public $show_label = true;
67
68
	/**
69
	 * @var string The custom class for this field.
70
	 * @api
71
	 * @since 2.0
72
	 */
73
	public $custom_class = '';
74
75
	/**
76
	 * @var string The capability required to view this field.
77
	 *
78
	 * If empty, anyone can view it, including non-logged in users.
79
	 *
80
	 * @api
81
	 * @since 2.0
82
	 */
83
	public $cap = '';
84
85
	/**
86
	 * @var bool Show as a link to entry.
87
	 *
88
	 * @api
89
	 * @since 2.0
90
	 */
91
	public $show_as_link = false;
92
93
	/**
94
	 * @var bool Filter this field from searching.
95
	 *
96
	 * @api
97
	 * @since 2.0
98
	 */
99
	public $search_filter = false;
100
101
	/**
102
	 * Return an array of the old format as used by callers of `GVCommon:get_directory_fields()` for example.
103
	 *
104
	 *  		'id' => string '9' (length=1)
105
	 *  		'label' => string 'Screenshots' (length=11)
106
	 *			'show_label' => string '1' (length=1)
107
	 *			'custom_label' => string '' (length=0)
108
	 *			'custom_class' => string 'gv-gallery' (length=10)
109
	 * 			'only_loggedin' => string '0' (length=1)
110
	 *			'only_loggedin_cap' => string 'read' (length=4)
111
	 *			'search_filter' => string '0'
112
	 *			'show_as_link' => string '0'
113
	 *
114
	 *			+ whatever else specific field types may have
115
	 *
116
	 * @internal
117
	 * @since 2.0
118
	 *
119
	 * @return array
120
	 */
121 72
	public function as_configuration() {
122 72
		return array_merge( array(
123 72
			'id' => $this->ID,
124 72
			'label' => $this->label,
125 72
			'show_label' => $this->show_label ? '1' : '0',
126 72
			'custom_label' => $this->custom_label,
127 72
			'custom_class' => $this->custom_class,
128 72
			'only_loggedin' => $this->cap ? '1' : '0',
129 72
			'only_loggedin_cap' => $this->cap,
130 72
			'search_filter' => $this->search_filter ? '1' : '0',
131 72
			'show_as_link' => $this->show_as_link ? '1' : '0',
132 72
		), $this->configuration );
133
	}
134
135
	/**
136
	 * An alias for \GV\Source::get_field()
137
	 *
138
	 * @see \GV\Source::get_field()
139
	 * @param string $source A \GV\Source class as string this field is tied to.
140
	 * @param array $args The arguments required for the backend to fetch the field (usually just the ID).
141
	 *
142
	 * @return \GV\Field|null A \GV\Field instance or null if not found.
143
	 */
144 1
	final public static function get( $source, $args ) {
145 1
		if ( ! is_string( $source ) || ! class_exists( $source ) ) {
146 1
			gravityview()->log->error( '{source} class not found', array( 'source' => $source ) );
147 1
			return null;
148
		}
149
150 1
		if ( ! method_exists( $source, 'get_field' ) ) {
151 1
			gravityview()->log->error( '{source} does not appear to be a valid \GV\Source subclass (get_field method missing)', array( 'source' => $source ) );
152 1
			return null;
153
		}
154
155 1
		return call_user_func_array( array( $source, 'get_field' ), is_array( $args ) ? $args : array( $args ) );
156
	}
157
158
	/**
159
	 * Create self from a configuration array.
160
	 *
161
	 * @param array $configuration The configuration array.
162
	 * @see \GV\Field::as_configuration()
163
	 * @internal
164
	 * @since 2.0
165
	 *
166
	 * @return \GV\Field The field implementation from configuration (\GV\GF_Field, \GV\Internal_Field).
167
	 */
168 72
	public static function from_configuration( $configuration ) {
169 72
		if ( empty( $configuration['id'] ) ) {
170 1
			$field = new self();
171 1
			gravityview()->log->error( 'Trying to get field from configuration without a field ID.', array( 'data' => $configuration ) );
172 1
			$field->update_configuration( $configuration );
173 1
			return $field;
174
		}
175
176
		/** Prevent infinte loops here from unimplemented children. */
177 72
		if ( version_compare( phpversion(), '5.4', '>=' ) ) {
178 72
			$trace = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 2 );
179
		} else {
180
			$trace = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS );
181
		}
182 72
		$trace = $trace[1];
183 72
		if ( $trace['function'] == 'from_configuration' && $trace['class'] == __CLASS__ ) {
0 ignored issues
show
introduced by
Found "== '". Use Yoda Condition checks, you must
Loading history...
184
			$field = new self();
185
			gravityview()->log->error( 'Infinite loop protection tripped. Returning default class here.' );
186
			$field->update_configuration( $configuration );
187
			return $field;
188
		}
189
190
		/** Determine the field implementation to use, and try to use. */
191 72
		$field_class = is_numeric( $configuration['id'] ) ? '\GV\GF_Field' : '\GV\Internal_Field';
192
193
		/**
194
		 * @filter `gravityview/field/class` Filter the field class about to be created from the configuration.
195
		 * @param string $field_class The field class about to be used.
196
		 * @param array $configuration The configuration as per \GV\Field::as_configuration()
197
		 */
198 72
		$field_class = apply_filters( 'gravityview/field/class', $field_class, $configuration );
199
200 72
		if ( ! class_exists( $field_class ) || ! method_exists( $field_class, 'from_configuration' ) ) {
201 1
			$field = new self();
202 1
			gravityview()->log->error( 'Class {field_class}::from_configuration does not exist.', array( 'field_class' => $field_class ) );
203 1
			$field->update_configuration( $configuration );
204 1
			return $field;
205
		}
206
207 72
		$field = $field_class::from_configuration( $configuration );
208
209 72
		if ( ! $field ) {
210 5
			$field = new self();
211 5
			gravityview()->log->error( 'Could not configure {field_class} with given configuration.', array( 'field_class' => __CLASS__, 'data' => $configuration ) );
212 5
			$field->update_configuration( $configuration );
213
		}
214
215 72
		return $field;
216
	}
217
218
	/**
219
	 * Update configuration.
220
	 *
221
	 * @param array $configuration The configuration array.
222
	 * @see \GV\Field::as_configuration()
223
	 * @since 2.0
224
	 *
225
	 * @return void
226
	 */
227 72
	public function update_configuration( $configuration ) {
228 72
		$configuration = wp_parse_args( $configuration, $this->as_configuration() );
229
230 72
		if ( $this->ID != $configuration['id'] ) {
231
			/** Smelling trouble here... */
232 5
			gravityview()->log->warning( 'ID is being changed for {field_class} instance, but implementation is not. Use ::from_configuration instead', array( 'field_class', __CLASS__ ) );
233
		}
234
235 72
		$this->ID = $configuration['id'];
236 72
		$this->label = $configuration['label'];
237 72
		$this->show_label = $configuration['show_label'] == '1';
238 72
		$this->custom_label = $configuration['custom_label'];
239 72
		$this->custom_class = $configuration['custom_class'];
240 72
		$this->cap = $configuration['only_loggedin'] == '1' ? $configuration['only_loggedin_cap'] : '';
241 72
		$this->search_filter = $configuration['search_filter'] == '1';
242 72
		$this->show_as_link = $configuration['show_as_link'] == '1';
243
244
		/** Shared among all field types (sort of). */
245
		$shared_configuration_keys = array(
246 72
			'id', 'label', 'show_label', 'custom_label', 'custom_class',
247
			'only_loggedin' ,'only_loggedin_cap', 'search_filter', 'show_as_link',
0 ignored issues
show
introduced by
Expected 0 spaces between "'only_loggedin'" and comma; 1 found
Loading history...
248
		);
249
250
		/** Everything else goes into the properties for now. @todo subclasses! */
251 72
		foreach ( $configuration as $key => $value ) {
252 72
			if ( ! in_array( $key, $shared_configuration_keys ) ) {
253 72
				$this->configuration[ $key ] = $value;
254
			}
255
		}
256 72
	}
257
258
	/**
259
	 * Retrieve the label for this field.
260
	 *
261
	 * @param \GV\View $view The view for this context if applicable.
262
	 * @param \GV\Source $source The source (form) for this context if applicable.
263
	 * @param \GV\Entry $entry The entry for this context if applicable.
264
	 * @param \GV\Request $request The request for this context if applicable.
265
	 *
266
	 * @return string The label for this field. Nothing here.
267
	 */
268 22
	public function get_label( View $view = null, Source $source = null, Entry $entry = null, Request $request = null ) {
269
270 22
		if ( ! $this->show_label ) {
271
			return '';
272
		}
273
274
		/** A custom label is available. */
275 22
		if ( ! empty( $this->custom_label ) ) {
276 1
			return \GravityView_API::replace_variables( $this->custom_label, $source ? $source->form ? : null : null, $entry ? $entry->as_entry() : null );
0 ignored issues
show
Bug introduced by
The property form does not seem to exist in GV\Source.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
277
		}
278
279 22
		return '';
280
	}
281
282
	/**
283
	 * Retrieve the value for this field.
284
	 *
285
	 * Returns null in this implementation (or, rather, lack thereof).
286
	 *
287
	 * @param \GV\View $view The view for this context if applicable.
288
	 * @param \GV\Source $source The source (form) for this context if applicable.
289
	 * @param \GV\Entry $entry The entry for this context if applicable.
290
	 * @param \GV\Request $request The request for this context if applicable.
291
	 *
292
	 * @return mixed The value for this field.
293
	 */
294 1
	public function get_value( View $view = null, Source $source = null, Entry $entry = null, Request $request = null ) {
295 1
		return $this->get_value_filters( null, $view, $source, $entry, $request );
296
	}
297
	
298
	/**
299
	 * Apply all the required filters after get_value() was called.
300
	 *
301
	 * @param mixed $value The value that will be filtered.
302
	 * @param \GV\View $view The view for this context if applicable.
303
	 * @param \GV\Source $source The source (form) for this context if applicable.
304
	 * @param \GV\Entry $entry The entry for this context if applicable.
305
	 * @param \GV\Request $request The request for this context if applicable.
306
	 *
307
	 * This is in its own function since \GV\Field subclasses have to call it.
308
	 */
309 54
	protected function get_value_filters( $value, View $view = null, Source $source = null, Entry $entry = null, Request $request = null ) {
310 54
		if ( $this->type ) {
0 ignored issues
show
Documentation introduced by
The property type does not exist on object<GV\Field>. 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...
311
			/**
312
			 * @filter `gravityview/field/$type/value` Override the displayed value here.
313
			 * @param string $value The value.
314
			 * @param \GV\Field The field we're doing this for.
315
			 * @param \GV\View $view The view for this context if applicable.
316
			 * @param \GV\Source $source The source (form) for this context if applicable.
317
			 * @param \GV\Entry $entry The entry for this context if applicable.
318
			 * @param \GV\Request $request The request for this context if applicable.
319
			 */
320 54
			$value = apply_filters( "gravityview/field/{$this->type}/value", $value, $this, $view, $source, $entry, $request );
0 ignored issues
show
Documentation introduced by
The property type does not exist on object<GV\Field>. 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...
321
		}
322
323
		/**
324
		 * @filter `gravityview/field/value` Override the displayed value here.
325
		 * @param string $value The value.
326
		 * @param \GV\Field The field we're doing this for.
327
		 * @param \GV\View $view The view for this context if applicable.
328
		 * @param \GV\Source $source The source (form) for this context if applicable.
329
		 * @param \GV\Entry $entry The entry for this context if applicable.
330
		 * @param \GV\Request $request The request for this context if applicable.
331
		 */
332 54
		return apply_filters( 'gravityview/field/value', $value, $this, $view, $source, $entry, $request );
333
	}
334
335 27
	public function is_visible() {
336
		/**
337
		 * @filter `gravityview/field/is_visible` Should this field be visible?
338
		 *
339
		 * @param boolean $visible Visible or not, defaults to the set field capability requirement if defined.
340
		 * @param \GV\Field $field The field we're looking at.
341
		 */
342 27
		return apply_filters( 'gravityview/field/is_visible', ( ! $this->cap || \GVCommon::has_cap( $this->cap ) ), $this );
343
	}
344
345
	/**
346
	 * Get one of the extra configuration keys via property accessors.
347
	 *
348
	 * @param string $key The key to get.
349
	 *
350
	 * @return mixed|null The value for the given configuration key, null if doesn't exist.
351
	 */
352 56
	public function __get( $key ) {
353 56
		switch( $key ):
354
			default:
0 ignored issues
show
Unused Code introduced by
default: if (isset($...figuration[$key]; } 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...
355 56
				if ( isset( $this->configuration[ $key ] ) ) {
356 18
					return $this->configuration[ $key ];
357
				}
358
		endswitch;
359 55
	}
360
361
	/**
362
	 * Is this set?
363
	 *
364
	 * @param string $key The key to get.
365
	 *
366
	 * @return boolean Whether this $key is set or not.
367
	 */
368 5
	public function __isset( $key ) {
369 5
		switch( $key ):
370
			default:
0 ignored issues
show
Unused Code introduced by
default: return isse...->configuration[$key]); 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...
371 5
				return isset( $this->configuration[ $key ] );
372
		endswitch;
373
	}
374
}
375