Completed
Push — develop ( 295efb...502043 )
by Zack
15:13
created

GravityView_Entry_Link_Shortcode::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 3
ccs 3
cts 3
cp 1
crap 1
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 10 and the first side effect is on line 362.

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
3
/**
4
 * Handle the [gv_entry_link] shortcode
5
 *
6
 * Replaces [gv_edit_entry_link] and [gv_delete_entry_link] shortcodes
7
 *
8
 * @since 1.15
9
 */
10
class GravityView_Entry_Link_Shortcode {
11
12
	/**
13
	 * @type array Entry fetched using the $atts['entry_id'] shortcode setting.
14
	 * @since 1.15
15
	 */
16
	private $entry = array();
17
18
	/**
19
	 * @type int If set, generate a link to the entry for this View ID. Required when used outside a View. Otherwise, current View ID is used.
20
	 * @since 1.15
21
	 */
22
	private $view_id = 0;
23
24
	/**
25
	 * @type array The accepted shortcode attribute pairs, with defaults set
26
	 * @since 1.15
27
	 */
28
	static private $defaults = array(
29
		'action'       => 'read',
30
		'view_id'      => 0,
31
		'entry_id'     => 0,
32
		'post_id'      => 0,
33
		'link_atts'    => '',
34
		'return'       => 'html',
35
		'field_values' => '',
36
	);
37
38
	/**
39
	 * @type array The final settings for the shortcode, after merging passed $atts with self::$defaults
40
	 * @since 1.15
41
	 */
42
	private $settings = array();
43
44 2
	function __construct() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
45 2
		$this->add_hooks();
46 2
	}
47
48
	/**
49
	 * Add shortcodes
50
	 *
51
	 * @since 1.15
52
	 */
53 2
	private function add_hooks() {
54 2
		add_shortcode( 'gv_entry_link', array( $this, 'read_shortcode' ) );
55 2
		add_shortcode( 'gv_edit_entry_link', array( $this, 'edit_shortcode' ) );
56 2
		add_shortcode( 'gv_delete_entry_link', array( $this, 'delete_shortcode' ) );
57 2
	}
58
59
	/**
60
	 * @since 1.15
61
	 * @copydoc GravityView_Entry_Link_Shortcode::shortcode
62
	 */
63 1
	public function read_shortcode( $atts, $content = null, $context = 'gv_entry_link' ) {
64 1
		return $this->shortcode( $atts, $content, $context );
65
	}
66
67
	/**
68
	 * Backward compatibility for existing `gv_edit_entry_link` shortcode
69
	 * Forces $atts['action'] to "edit"
70
	 *
71
	 * @since 1.15
72
	 * @copydoc GravityView_Entry_Link_Shortcode::shortcode
73
	 */
74
	public function edit_shortcode( $atts = array(), $content = null, $context = 'gv_edit_entry_link' ) {
75
76
		$atts = shortcode_atts( self::$defaults, $atts );
77
78
		$atts['action'] = 'edit';
79
80
		return $this->shortcode( $atts, $content, $context );
81
	}
82
83
	/**
84
	 * Backward compatibility for existing `gv_delete_entry_link` shortcodes
85
	 * Forces $atts['action'] to "delete"
86
	 *
87
	 * @since 1.15
88
	 * @copydoc GravityView_Entry_Link_Shortcode::shortcode
89
	 */
90
	public function delete_shortcode( $atts = array(), $content = null, $context = 'gv_delete_entry_link' ) {
91
92
		$atts = shortcode_atts( self::$defaults, $atts );
93
94
		$atts['action'] = 'delete';
95
96
		return $this->shortcode( $atts, $content, $context );
97
	}
98
99
	/**
100
	 * Generate a link to an entry. The link can be an edit, delete, or standard link.
101
	 *
102
	 * @since 1.15
103
	 *
104
	 * @param array $atts {
105
	 *    @type string $action What type of link to generate. Options: `read`, `edit`, and `delete`. Default: `read`
106
	 *    @type string $view_id Define the ID for the View. If not set, use current View ID, if exists.
107
	 *    @type string $entry_id ID of the entry to edit. If undefined, uses the current entry ID, if exists.
108
	 *    @type string $post_id ID of the base post or page to use for an embedded View
109
	 *    @type string $link_atts Pass anchor tag attributes (`target=_blank` to open Edit Entry link in a new window, for example)
110
	 *    @type string $return What should the shortcode return: link HTML (`html`) or the URL (`url`). Default: `html`
111
	 *    @type string $field_values Only used for `action="edit"`. Parameters to pass in to the prefill data in Edit Entry form. Uses the same format as Gravity Forms "Allow field to be populated dynamically" {@see https://www.gravityhelp.com/documentation/article/allow-field-to-be-populated-dynamically/ }
112
	 * }
113
	 *
114
	 * @param string|null $content Used as link anchor text, if specified.
115
	 * @param string $context Current shortcode being called. Not used.
116
	 *
117
	 * @return null|string If admin or an error occurred, returns null. Otherwise, returns entry link output. If `$atts['return']` is 'url', the entry link URL. Otherwise, entry link `<a>` HTML tag.
118
	 */
119 2
	private function shortcode( $atts, $content = null, $context = 'gv_entry_link' ) {
120
		// Don't process when saving post. Keep processing if it's admin-ajax.php
121 2
		if ( gravityview()->request->is_admin() ) {
122
			return null;
123
		}
124
125
		// Make sure GV is loaded
126 2
		if ( ! class_exists( 'GravityView_frontend' ) || ! class_exists( 'GravityView_View' ) ) {
127
			gravityview()->log->error( 'GravityView_frontend or GravityView_View do not exist.' );
128
129
			return null;
130
		}
131
132 2
		$this->settings = shortcode_atts( self::$defaults, $atts, $context );
133
134 2
		$this->view_id = empty( $this->settings['view_id'] ) ? GravityView_View::getInstance()->getViewId() : absint( $this->settings['view_id'] );
135
136 2
		if ( empty( $this->view_id ) ) {
137 1
			gravityview()->log->error( 'A View ID was not defined and we are not inside a View' );
138
139 1
			return null;
140
		}
141
142 2
		$this->entry = $this->get_entry( $this->settings['entry_id'] );
143
144 2
		if ( empty( $this->entry ) ) {
145 1
			gravityview()->log->error( 'An Entry ID was not defined or found. Entry ID: {entry_id}', array( 'entry_id' => $this->settings['entry_id'] ) );
146
147 1
			return null;
148
		}
149
150 2
		gravityview()->log->debug( '{context} atts:', array( 'context' => $context, 'data' => $atts ) );
151
152 2
		if ( ! $this->has_cap() ) {
153 1
			gravityview()->log->error( 'User does not have the capability to {action} this entry: {entry_id}', array( 'action' => esc_attr( $this->settings['action'] ), 'entry_id' => $this->entry['id'] ) );
154
155 1
			return null;
156
		}
157
158 2
		$url = $this->get_url();
159
160 2
		if ( ! $url ) {
161
			gravityview()->log->error( 'Link returned false; View or Post may not exist.' );
162
163
			return false;
164
		}
165
166
		// Get just the URL, not the tag
167 2
		if ( 'url' === $this->settings['return'] ) {
168 1
			return $url;
169
		}
170
171 2
		$link_atts = $this->get_link_atts();
172
173 2
		$link_text = $this->get_anchor_text( $content );
174
175 2
		$return = gravityview_get_link( $url, $link_text, $link_atts );
176
177
		/**
178
		 * @filter `gravityview/shortcodes/gv_entry_link/output` Modify the output of the [gv_entry_link] shortcode
179
		 * @since 2.0.15
180
		 * @param string $return The HTML link output
181
		 * @param array {
182
		 *   @type string        $url The URL used to generate the anchor tag. {@see GravityView_Entry_Link_Shortcode::get_url}
183
		 *   @type string        $link_text {@see GravityView_Entry_Link_Shortcode::get_anchor_text}
184
		 *   @type array         $link_atts {@see GravityView_Entry_Link_Shortcode::get_link_atts}
185
		 *   @type array|string  $atts Shortcode atts passed to shortcode
186
		 *   @type string        $content Content passed to shortcode
187
		 *   @type string        $context The tag of the shortcode being called
188
		 * }
189
		 */
190 2
		$return = apply_filters( 'gravityview/shortcodes/gv_entry_link/output', $return, compact( 'url', 'link_text', 'link_atts', 'atts', 'content', 'context' ) );
191
192 2
		return $return;
193
	}
194
195
	/**
196
	 * Parse shortcode atts to fetch `link_atts`, which will be added to the output of the HTML anchor tag generated by shortcode
197
	 * Only used when `return` value of shortcode is not "url"
198
	 *
199
	 * @since 1.15
200
	 * @see gravityview_get_link() See acceptable attributes here
201
	 * @return array Array of attributes to be added
202
	 */
203 1
	private function get_link_atts() {
204
205 1
		wp_parse_str( $this->settings['link_atts'], $link_atts );
0 ignored issues
show
Bug introduced by
The variable $link_atts seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
206
207 1
		if ( 'delete' === $this->settings['action'] ) {
208
			$link_atts['onclick'] = isset( $link_atts['onclick'] ) ? $link_atts['onclick'] : GravityView_Delete_Entry::get_confirm_dialog();
0 ignored issues
show
Bug introduced by
The variable $link_atts 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...
209
		}
210
211 1
		return (array) $link_atts;
212
	}
213
214
	/**
215
	 * Get the anchor text for the link. If content inside shortcode is defined, use that as the text. Otherwise, use default values.
216
	 *
217
	 * Only used when `return` value of shortcode is not "url"
218
	 *
219
	 * @since 1.15
220
	 *
221
	 * @param string|null $content Content inside shortcode, if defined
222
	 *
223
	 * @return string Text to use for HTML anchor
224
	 */
225 1
	private function get_anchor_text( $content = null ) {
226
227 1
		if ( $content ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $content of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
228 1
			return do_shortcode( $content );
229
		}
230
231
		switch ( $this->settings['action'] ) {
232
			case 'edit':
233
				$anchor_text = __( 'Edit Entry', 'gravityview' );
234
				break;
235
			case 'delete':
236
				$anchor_text = __( 'Delete Entry', 'gravityview' );
237
				break;
238
			default:
239
				$anchor_text = __( 'View Details', 'gravityview' );
240
		}
241
242
		return $anchor_text;
243
	}
244
245
	/**
246
	 * Get the URL for the entry.
247
	 *
248
	 * Uses the `post_id`, `view_id` params as defined in the shortcode attributes.
249
	 *
250
	 * @since 1.15
251
	 *
252
	 * @param string|null $content Content inside shortcode, if defined
0 ignored issues
show
Bug introduced by
There is no parameter named $content. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
253
	 *
254
	 * @return string|boolean If URL is fetched, the URL to the entry link. If not found, returns false.
255
	 */
256 1
	private function get_url() {
257
258
		// if post_id is not defined, default to view_id
259 1
		$post_id = empty( $this->settings['post_id'] ) ? $this->view_id : $this->settings['post_id'];
260
261 1
		switch ( $this->settings['action'] ) {
262 1
			case 'edit':
263
				$url = GravityView_Edit_Entry::get_edit_link( $this->entry, $this->view_id, $post_id );
264
				break;
265 1
			case 'delete':
266
				$url = GravityView_Delete_Entry::get_delete_link( $this->entry, $this->view_id, $post_id );
267
				break;
268 1
			case 'read':
269
			default:
270 1
				$url = GravityView_API::entry_link( $this->entry, $post_id );
271
		}
272
273 1
		$url = $this->maybe_add_field_values_query_args( $url );
274
275 1
		return $url;
276
	}
277
278
	/**
279
	 * Check whether the user has the capability to see the shortcode output, depending on the action ('read', 'edit', 'delete')
280
	 *
281
	 * @since 1.15
282
	 * @return bool True: has cap.
283
	 */
284 1
	private function has_cap() {
285
286 1
		switch ( $this->settings['action'] ) {
287 1
			case 'edit':
288
				$has_cap = GravityView_Edit_Entry::check_user_cap_edit_entry( $this->entry, $this->view_id );
289
				break;
290 1
			case 'delete':
291
				$has_cap = GravityView_Delete_Entry::check_user_cap_delete_entry( $this->entry, array(), $this->view_id );
292
				break;
293 1
			case 'read':
294
			default:
295 1
				$has_cap = true; // TODO: add cap check for read_gravityview
296
		}
297
298 1
		return $has_cap;
299
	}
300
301
	/**
302
	 * Get entry array from `entry_id` parameter. If no $entry_id
303
	 *
304
	 * @since 1.15
305
	 * @uses GVCommon::get_entry
306
	 * @uses GravityView_frontend::getSingleEntry
307
	 *
308
	 * @param int $entry_id Gravity Forms Entry ID. If not passed, current View's current entry ID will be used, if found.
309
	 *
310
	 * @return array|bool Gravity Forms array, if found. Otherwise, false.
311
	 */
312 1
	private function get_entry( $entry_id = 0 ) {
313
314 1
		$backup_entry = GravityView_frontend::getInstance()->getSingleEntry() ? GravityView_frontend::getInstance()->getEntry() : GravityView_View::getInstance()->getCurrentEntry();
315
316 1
		if ( empty( $entry_id ) ) {
317 1
			if ( ! $backup_entry ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $backup_entry of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
318
				gravityview()->log->error( 'No entry defined (or entry id not valid number)', array( 'data' => $this->settings ) );
319
320
				return false;
321
			}
322 1
			$entry = $backup_entry;
323
		} else {
324 1
			$entry = wp_cache_get( 'gv_entry_link_entry_' . $entry_id, 'gravityview_entry_link_shortcode' );
325 1
			if ( false === $entry ) {
326 1
				$entry = GVCommon::get_entry( $entry_id, true, false );
327 1
				wp_cache_add( 'gv_entry_link_entry_' . $entry_id, $entry, 'gravityview_entry_link_shortcode' );
328
			}
329
		}
330
331
		// No search results
332 1
		if ( false === $entry ) {
333
			gravityview()->log->error( 'No entries match the entry ID defined: {entry_id}', array( 'entry_id' => $entry_id ) );
334
335
			return false;
336
		}
337
338 1
		return $entry;
339
	}
340
341
	/**
342
	 * Allow passing URL params to dynamically populate the Edit Entry form
343
	 * If `field_values` key is set, run it through `parse_str()` and add the values to $url
344
	 *
345
	 * @since 1.15
346
	 *
347
	 * @param string $href URL
0 ignored issues
show
Bug introduced by
There is no parameter named $href. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
348
	 */
349 1
	private function maybe_add_field_values_query_args( $url ) {
350
351 1
		if ( $url && ! empty( $this->settings['field_values'] ) ) {
352
353
			wp_parse_str( $this->settings['field_values'], $field_values );
0 ignored issues
show
Bug introduced by
The variable $field_values 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...
354
355
			$url = add_query_arg( $field_values, $url );
356
		}
357
358 1
		return $url;
359
	}
360
}
361
362
new GravityView_Entry_Link_Shortcode;