Completed
Pull Request — 2.x (#4569)
by Scott Kingsley
08:49
created

PodsField_Link::value()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 5
dl 0
loc 5
rs 9.4285
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 7 and the first side effect is on line 2.

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
require_once PODS_DIR . 'classes/fields/website.php';
3
4
/**
5
 * @package Pods\Fields
6
 */
7
class PodsField_Link extends PodsField_Website {
8
9
	/**
10
	 * {@inheritdoc}
11
	 */
12
	public static $group = 'Text';
13
14
	/**
15
	 * {@inheritdoc}
16
	 */
17
	public static $type = 'link';
18
19
	/**
20
	 * {@inheritdoc}
21
	 */
22
	public static $label = 'Link';
23
24
	/**
25
	 * {@inheritdoc}
26
	 */
27
	public static $prepare = '%s';
28
29
	/**
30
	 * {@inheritdoc}
31
	 */
32
	public function setup() {
33
34
		self::$label = __( 'Link', 'pods' );
35
	}
36
37
	/**
38
	 * {@inheritdoc}
39
	 */
40
	public function options() {
41
42
		$options = array(
43
			static::$type . '_format'            => array(
44
				'label'   => __( 'Format', 'pods' ),
45
				'default' => 'normal',
46
				'type'    => 'pick',
47
				'data'    => array(
48
					'none'              => __( 'No URL format restrictions', 'pods' ),
49
					'normal'            => __( 'http://example.com/', 'pods' ),
50
					'no-www'            => __( 'http://example.com/ (remove www)', 'pods' ),
51
					'force-www'         => __( 'http://www.example.com/ (force www if no sub-domain provided)', 'pods' ),
52
					'no-http'           => __( 'example.com', 'pods' ),
53
					'no-http-no-www'    => __( 'example.com (force removal of www)', 'pods' ),
54
					'no-http-force-www' => __( 'www.example.com (force www if no sub-domain provided)', 'pods' ),
55
				),
56
			),
57
			static::$type . '_select_existing'   => array(
58
				'label'      => __( 'Enable Selecting from Existing Links?', 'pods' ),
59
				'default'    => 1,
60
				'type'       => 'boolean',
61
				'dependency' => true,
62
			),
63
			static::$type . '_new_window'        => array(
64
				'label'      => __( 'Open link in new window by default?', 'pods' ),
65
				'default'    => apply_filters( 'pods_form_ui_field_link_new_window', 0, static::$type ),
66
				'type'       => 'boolean',
67
				'dependency' => false,
68
			),
69
			'output_options'                     => array(
70
				'label' => __( 'Link Text Output Options', 'pods' ),
71
				'group' => array(
72
					static::$type . '_allow_shortcode' => array(
73
						'label'      => __( 'Allow Shortcodes?', 'pods' ),
74
						'default'    => 0,
75
						'type'       => 'boolean',
76
						'dependency' => true,
77
					),
78
					static::$type . '_allow_html'      => array(
79
						'label'      => __( 'Allow HTML?', 'pods' ),
80
						'default'    => 0,
81
						'type'       => 'boolean',
82
						'dependency' => true,
83
					),
84
				),
85
			),
86
			static::$type . '_allowed_html_tags' => array(
87
				'label'      => __( 'Allowed HTML Tags', 'pods' ),
88
				'depends-on' => array( static::$type . '_allow_html' => true ),
89
				'default'    => 'strong em a ul ol li b i',
90
				'type'       => 'text',
91
			),
92
			static::$type . '_html5'             => array(
93
				'label'   => __( 'Enable HTML5 Input Field?', 'pods' ),
94
				'default' => apply_filters( 'pods_form_ui_field_html5', 0, static::$type ),
95
				'type'    => 'boolean',
96
			),
97
		);
98
99
		return $options;
100
101
	}
102
103
	/**
104
	 * {@inheritdoc}
105
	 */
106
	public function schema( $options = null ) {
107
108
		$schema = 'LONGTEXT';
109
110
		return $schema;
111
112
	}
113
114
	/**
115
	 * {@inheritdoc}
116
	 */
117
	public function display( $value = null, $name = null, $options = null, $pod = null, $id = null ) {
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
118
119
		// Validate for an array because display is also used for the get_post_meta filters along the function chain
120
		if ( ! is_array( $value ) ) {
121
			return $value;
122
		}
123
124
		// Ensure proper format
125
		$value = $this->pre_save( $value, $id, $name, $options, null, $pod );
126
127
		if ( ! empty( $value['text'] ) ) {
128
			$value['text'] = $this->strip_html( $value['text'], $options );
129
		}
130
131
		if ( ! empty( $value['url'] ) ) {
132
133
			$link = '<a href="%s"%s>%s</a>';
134
135
			// Build the URL
136
			$url = $this->build_url( wp_parse_url( $value['url'] ) );
137
138
			// Display URL as text by default. If text provided, use the text input
139
			$text = $url;
140
141
			if ( ! empty( $value['text'] ) ) {
142
				$text = $value['text'];
143
			}
144
145
			$atts = '';
146
147
			if ( ! empty( $value['target'] ) || ( ! isset( $value['target'] ) && 1 === (int) pods_v( static::$type . '_new_window', $options ) ) ) {
148
				// Possible support for other targets in future
149
				$atts .= ' target="' . esc_attr( $value['target'] ) . '"';
150
			}
151
152
			// Do shortcodes if this is enabled
153
			if ( 1 === (int) pods_v( static::$type . '_allow_shortcode', $options ) ) {
154
				$text = do_shortcode( $text );
155
			}
156
157
			// Return the value
158
			$value = sprintf( $link, esc_url( $url ), $atts, $text );
159
160
		} elseif ( ! empty( $value['text'] ) ) {
161
			// No URL data found (probably database error), return text is this is available
162
			$value = $value['text'];
163
		}//end if
164
165
		// Return database value or display value if above conditions are met
166
		return $value;
0 ignored issues
show
Bug Compatibility introduced by
The expression return $value; of type string|array is incompatible with the return type of the parent method PodsField_Website::display of type string as it can also be of type array which is not included in this return type.
Loading history...
167
168
	}
169
170
	/**
171
	 * Change the way the a list of values of the field are displayed with Pods::field
172
	 *
173
	 * @param mixed|null  $value   Field value.
174
	 * @param string|null $name    Field name.
175
	 * @param array|null  $options Field options.
176
	 * @param array|null  $pod     Pod options.
177
	 * @param int|null    $id      Item ID.
178
	 *
179
	 * @return mixed|null|string
180
	 *
181
	 * @since 2.7
182
	 */
183
	public function display_list( $value = null, $name = null, $options = null, $pod = null, $id = null ) {
184
185
		return call_user_func_array( array( $this, 'display' ), func_get_args() );
186
187
	}
188
189
	/**
190
	 * {@inheritdoc}
191
	 */
192
	public function input( $name, $value = null, $options = null, $pod = null, $id = null ) {
193
194
		$options         = (array) $options;
195
		$form_field_type = PodsForm::$field_type;
196
		$field_type      = 'link';
197
198
		// Ensure proper format
199
		$value = $this->pre_save( $value, $id, $name, $options, null, $pod );
200
201
		pods_view( PODS_DIR . 'ui/fields/' . $field_type . '.php', compact( array_keys( get_defined_vars() ) ) );
202
203
	}
204
205
	/**
206
	 * {@inheritdoc}
207
	 */
208
	public function validate( $value, $name = null, $options = null, $fields = null, $pod = null, $id = null, $params = null ) {
209
210
		$errors = array();
211
212
		$label = strip_tags( pods_v( 'label', $options, ucwords( str_replace( '_', ' ', $name ) ) ) );
213
214
		$check = $this->pre_save( $value, $id, $name, $options, $fields, $pod, $params );
215
216
		$check = $check['url'];
217
218
		if ( is_array( $check ) ) {
219
			$errors = $check;
220
		} else {
221
			if ( ! empty( $value['url'] ) && 0 < strlen( $value['url'] ) && '' === $check ) {
222
				if ( 1 === (int) pods_v( 'required', $options ) ) {
223
					$errors[] = sprintf( __( 'The %s field is required.', 'pods' ), $label );
224
				} else {
225
					$errors[] = sprintf( __( 'Invalid link provided for the field %s.', 'pods' ), $label );
226
				}
227
			}
228
		}
229
230
		if ( ! empty( $errors ) ) {
231
			return $errors;
232
		}
233
234
		return true;
235
236
	}
237
238
	/**
239
	 * {@inheritdoc}
240
	 */
241
	public function pre_save( $value, $id = null, $name = null, $options = null, $fields = null, $pod = null, $params = null ) {
242
243
		$options = (array) $options;
244
245
		// Update from a single (non array) input field (like website) if the field updates
246
		if ( is_string( $value ) ) {
247
			$value = array( 'url' => $value );
248
		}
249
250
		$value = array_merge(
251
			array(
252
				'url'    => '',
253
				'text'   => '',
254
				'target' => '',
255
			), (array) $value
256
		);
257
258
		// Start URL format
259
		if ( ! empty( $value['url'] ) ) {
260
			$value['url'] = $this->validate_url( $value['url'], $options );
261
		}
262
263
		// Start Title format
264
		if ( ! empty( $value['text'] ) ) {
265
			$value['text'] = $this->strip_html( $value['text'], $options );
266
		}
267
268
		// Start Target format
269
		if ( ! empty( $value['target'] ) ) {
270
			$value['target'] = $this->validate_target( $value['target'] );
271
		} elseif ( ! isset( $value['target'] ) && 1 === (int) pods_v( static::$type . '_new_window', $options, 0 ) ) {
272
			$value['target'] = '_blank';
273
		}
274
275
		return $value;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $value; (array) is incompatible with the return type of the parent method PodsField_Website::pre_save of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
276
277
	}
278
279
	/**
280
	 * Init the editor needed for WP Link modal to work
281
	 */
282
	public function validate_link_modal() {
283
284
		static $init;
285
286
		if ( empty( $init ) ) {
287
			if ( ! did_action( 'wp_enqueue_editor' ) ) {
288
				add_action( 'shutdown', array( $this, 'add_link_modal' ) );
289
			}
290
		}
291
292
		$init = true;
293
294
	}
295
296
	/**
297
	 * Echo the link modal code
298
	 */
299
	public function add_link_modal() {
300
301
		if ( ! class_exists( '_WP_Editors', false ) && file_exists( ABSPATH . WPINC . '/class-wp-editor.php' ) ) {
302
			require_once ABSPATH . WPINC . '/class-wp-editor.php';
303
		}
304
305
		if ( class_exists( '_WP_Editors' ) && method_exists( '_WP_Editors', 'wp_link_dialog' ) ) {
306
			_WP_Editors::wp_link_dialog();
307
		} else {
308
			echo '<div style="display:none;">';
309
			wp_editor( '', 'pods-link-editor-hidden' );
310
			echo '</div>';
311
		}
312
313
	}
314
}
315