Completed
Push — add/sal-post ( 86e404...770b13 )
by
unknown
09:04
created

WPCOM_JSON_API_Post_v1_1_Endpoint   C

Complexity

Total Complexity 74

Size/Duplication

Total Lines 340
Duplicated Lines 26.18 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 74
lcom 1
cbo 4
dl 89
loc 340
rs 5.5244
c 1
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 9 9 4
D get_post_by() 10 45 9
A get_sal_post_by() 0 11 2
D render_response_keys() 0 134 43
A get_blog_post() 10 10 3
C win8_gallery_shortcode() 60 60 13

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like WPCOM_JSON_API_Post_v1_1_Endpoint often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use WPCOM_JSON_API_Post_v1_1_Endpoint, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
abstract class WPCOM_JSON_API_Post_v1_1_Endpoint extends WPCOM_JSON_API_Endpoint {
4
	public $post_object_format = array(
5
		// explicitly document and cast all output
6
		'ID'                => '(int) The post ID.',
7
		'site_ID'		    => '(int) The site ID.',
8
		'author'            => '(object>author) The author of the post.',
9
		'date'              => "(ISO 8601 datetime) The post's creation time.",
10
		'modified'          => "(ISO 8601 datetime) The post's most recent update time.",
11
		'title'             => '(HTML) <code>context</code> dependent.',
12
		'URL'               => '(URL) The full permalink URL to the post.',
13
		'short_URL'         => '(URL) The wp.me short URL.',
14
		'content'           => '(HTML) <code>context</code> dependent.',
15
		'excerpt'           => '(HTML) <code>context</code> dependent.',
16
		'slug'              => '(string) The name (slug) for the post, used in URLs.',
17
		'guid'              => '(string) The GUID for the post.',
18
		'status'            => array(
19
			'publish'           => 'The post is published.',
20
			'draft'             => 'The post is saved as a draft.',
21
			'pending'           => 'The post is pending editorial approval.',
22
			'private'           => 'The post is published privately',
23
			'future'            => 'The post is scheduled for future publishing.',
24
			'trash'             => 'The post is in the trash.',
25
			'auto-draft'        => 'The post is a placeholder for a new post.',
26
		),
27
		'sticky'            => '(bool) Is the post sticky?',
28
		'password'          => '(string) The plaintext password protecting the post, or, more likely, the empty string if the post is not password protected.',
29
		'parent'            => "(object>post_reference|false) A reference to the post's parent, if it has one.",
30
		'type'              => "(string) The post's post_type. Post types besides post, page and revision need to be whitelisted using the <code>rest_api_allowed_post_types</code> filter.",
31
		'discussion'        => '(object) Hash of discussion options for the post',
32
		'likes_enabled'     => "(bool) Is the post open to likes?",
33
		'sharing_enabled'   => "(bool) Should sharing buttons show on this post?",
34
		'like_count'        => '(int) The number of likes for this post.',
35
		'i_like'            => '(bool) Does the current user like this post?',
36
		'is_reblogged'      => '(bool) Did the current user reblog this post?',
37
		'is_following'      => '(bool) Is the current user following this blog?',
38
		'global_ID'         => '(string) A unique WordPress.com-wide representation of a post.',
39
		'featured_image'    => '(URL) The URL to the featured image for this post if it has one.',
40
		'post_thumbnail'    => '(object>attachment) The attachment object for the featured image if it has one.',
41
		'format'            => array(), // see constructor
42
		'geo'               => '(object>geo|false)',
43
		'menu_order'        => '(int) (Pages Only) The order pages should appear in.',
44
		'page_template'     => '(string) (Pages Only) The page template this page is using.',
45
		'publicize_URLs'    => '(array:URL) Array of Twitter and Facebook URLs published by this post.',
46
		'tags'              => '(object:tag) Hash of tags (keyed by tag name) applied to the post.',
47
		'categories'        => '(object:category) Hash of categories (keyed by category name) applied to the post.',
48
		'attachments'	    => '(object:attachment) Hash of post attachments (keyed by attachment ID). Returns the most recent 20 attachments. Use the `/sites/$site/media` endpoint to query the attachments beyond the default of 20 that are returned here.',
49
		'attachment_count'  => '(int) The total number of attachments for this post. Use the `/sites/$site/media` endpoint to query the attachments beyond the default of 20 that are returned here.',
50
		'metadata'	        => '(array) Array of post metadata keys and values. All unprotected meta keys are available by default for read requests. Both unprotected and protected meta keys are available for authenticated requests with access. Protected meta keys can be made available with the <code>rest_api_allowed_public_metadata</code> filter.',
51
		'meta'              => '(object) API result meta data',
52
		'capabilities'      => '(object) List of post-specific permissions for the user; publish_post, edit_post, delete_post',
53
		'revisions'         => '(array) List of post revision IDs. Only available for posts retrieved with context=edit.',
54
		'other_URLs'        => '(object) List of URLs for this post. Permalink and slug suggestions.',
55
	);
56
57
	// public $response_format =& $this->post_object_format;
58
59 View Code Duplication
	function __construct( $args ) {
60
		if ( is_array( $this->post_object_format ) && isset( $this->post_object_format['format'] ) ) {
61
			$this->post_object_format['format'] = get_post_format_strings();
62
		}
63
		if ( !$this->response_format ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->response_format 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...
64
			$this->response_format =& $this->post_object_format;
65
		}
66
		parent::__construct( $args );
67
	}
68
69
	/**
70
	 * Get a post by a specified field and value
71
	 *
72
	 * @param string $field
73
	 * @param string $field_value
74
	 * @param string $context Post use context (e.g. 'display')
75
	 * @return array Post
76
	 **/
77
	function get_post_by( $field, $field_value, $context = 'display' ) {
78
79
		// validate input
80
		if ( ! in_array( $field, array( 'ID', 'name' ) ) ) {
81
			return new WP_Error( 'invalid_field', 'Invalid API FIELD', 400 );
82
		}
83
84
		if ( ! in_array( $context, array( 'display', 'edit' ) ) ) {
85
			return new WP_Error( 'invalid_context', 'Invalid API CONTEXT', 400 );
86
		}
87
88
		// WTF is this?? Hacks!
89 View Code Duplication
		if ( 'display' === $context ) {
90
			$args = $this->query_args();
91
			if ( isset( $args['content_width'] ) && $args['content_width'] ) {
92
				$GLOBALS['content_width'] = (int) $args['content_width'];
93
			}
94
		}
95
96
		// WTF is this?? Why is this responsibility here? Hacks!
97 View Code Duplication
		if ( strpos( $_SERVER['HTTP_USER_AGENT'], 'wp-windows8' ) ) {
98
			remove_shortcode( 'gallery', 'gallery_shortcode' );
99
			add_shortcode( 'gallery', array( &$this, 'win8_gallery_shortcode' ) );
100
		}
101
102
		// fetch SAL site and post
103
		$post = $this->get_sal_post_by( $field, $field_value, $context );
104
105
		if ( is_wp_error( $post ) ) {
106
			return $post;
107
		} 
108
109
		$GLOBALS['post'] = $post;
110
111
		// TODO: not sure where this one should go
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
112
		if ( 'display' === $context ) {
113
			setup_postdata( $post );
114
		}
115
116
		$response = $this->render_response_keys( $post, $context, array_keys( $this->post_object_format ) );
117
118
		unset( $GLOBALS['post'] );
119
120
		return $response;
121
	}
122
123
	protected function get_sal_post_by( $field, $field_value, $context ) {
124
		global $blog_id;
125
126
		$site = $this->get_platform()->get_site( $blog_id );
127
128
		$post = ( $field === 'name' ) ?
129
			$site->get_post_by_name( $field_value, $context ) : 
130
			$site->get_post_by_id( $field_value, $context );
131
132
		return $post;
133
	}
134
135
	private function render_response_keys( $post, $context, $keys ) {
0 ignored issues
show
Unused Code introduced by
The parameter $context 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...
136
		foreach ( $keys as $key ) {
137
			switch ( $key ) {
138
			case 'ID' :
139
				// explicitly cast all output
140
				$response[$key] = (int) $post->ID;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$response was never initialized. Although not strictly required by PHP, it is generally a good practice to add $response = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
141
				break;
142
			case 'site_ID' :
143
				$response[$key] = $post->site->blog_id;
0 ignored issues
show
Bug introduced by
The variable $response 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...
144
				break;
145
			case 'author' :
146
				$response[$key] = $post->get_author();
147
				break;
148
			case 'date' :
149
				$response[$key] = $post->get_date();
150
				break;
151
			case 'modified' :
152
				$response[$key] = $post->get_modified_date();
153
				break;
154
			case 'title' :
155
				$response[$key] = $post->get_title();
156
				break;
157
			case 'URL' :
158
				$response[$key] = $post->get_url();
159
				break;
160
			case 'short_URL' :
161
				$response[$key] = $post->get_shortlink();
162
				break;
163
			case 'content' :
164
				$response[$key] = $post->get_content();
165
				break;
166
			case 'excerpt' :
167
				$response[$key] = $post->get_excerpt();
168
				break;
169
			case 'status' :
170
				$response[$key] = $post->get_status();
171
				break;
172
			case 'sticky' :
173
				$response[$key] = $post->is_sticky();
174
				break;
175
			case 'slug' :
176
				$response[$key] = $post->get_slug();
177
				break;
178
			case 'guid' :
179
				$response[$key] = $post->get_guid();
180
				break;
181
			case 'password' :
182
				$response[$key] = $post->get_password();
183
				break;
184
			case 'parent' : // (object|false)
185
				$response[$key] = $post->get_parent();
186
				break;
187
			case 'type' :
188
				$response[$key] = $post->get_type();
189
				break;
190
			case 'discussion' :
191
				$response[$key] = $post->get_discussion();
192
				break;
193
			case 'likes_enabled' :
194
				$response[$key] = $post->is_likes_enabled();
195
				break;
196
			case 'sharing_enabled' :
197
				$response[$key] = $post->is_sharing_enabled();
198
				break;
199
			case 'like_count' :
200
				$response[$key] = $post->get_like_count();
201
				break;
202
			case 'i_like'     :
203
				$response[$key] = $post->is_liked();
204
				break;
205
			case 'is_reblogged':
206
				$response[$key] = $post->is_reblogged();
207
				break;
208
			case 'is_following':
209
				$response[$key] = $post->is_following();
210
				break;
211
			case 'global_ID':
212
				$response[$key] = $post->get_global_id();
213
				break;
214
			case 'featured_image' :
215
				$response[$key] = $post->get_featured_image();
216
				break;
217
			case 'post_thumbnail' :
218
				$response[$key] = $post->get_post_thumbnail();
219
				break;
220
			case 'format' :
221
				$response[$key] = $post->get_format();
222
				break;
223
			case 'geo' : // (object|false)
224
				$response[$key] = $post->get_geo();
225
				break;
226
			case 'menu_order':
227
				$response[$key] = $post->get_menu_order();
228
				break;
229
			case 'page_template':
230
				$response[$key] = $post->get_page_template();
231
				break;
232
			case 'publicize_URLs' :
233
				$response[$key] = $post->get_publicize_urls();
234
				break;
235
			case 'tags' :
236
				$response[$key] = $post->get_tags();
237
				break;
238
			case 'categories':
239
				$response[$key] = $post->get_categories();
240
				break;
241
			case 'attachments':
242
				list( $attachments, $attachment_count ) = $post->get_attachments_and_count();
243
				$response[$key] = $attachments;
244
				$response['attachment_count'] = $attachment_count;
245
				break;
246
			case 'metadata' : // (array|false)
247
				$response[$key] = $post->get_metadata();
248
				break;
249
			case 'meta' :
250
				$response[$key] = $post->get_meta();
251
				break;
252
			case 'capabilities' :
253
				$response[$key] = $post->get_current_user_capabilities();
254
				break;
255
			case 'revisions' :
256
				$revisions = $post->get_revisions();
257
				if ( $revisions ) {
258
					$response[$key] = $revisions;
259
				}
260
				break;
261
			case 'other_URLs' :
262
				$response[$key] = $post->get_other_urls();
263
				break;
264
			}
265
		}
266
267
		return $response;
268
	}
269
270
	// TODO: factor this out
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
271 View Code Duplication
	function get_blog_post( $blog_id, $post_id, $context = 'display' ) {
272
		$blog_id = $this->api->get_blog_id( $blog_id );
273
		if ( !$blog_id || is_wp_error( $blog_id ) ) {
274
			return $blog_id;
275
		}
276
		switch_to_blog( $blog_id );
277
		$post = $this->get_post_by( 'ID', $post_id, $context );
278
		restore_current_blog();
279
		return $post;
280
	}
281
282 View Code Duplication
	function win8_gallery_shortcode( $attr ) {
283
		global $post;
284
285
		static $instance = 0;
286
		$instance++;
287
288
		$output = '';
289
290
		// We're trusting author input, so let's at least make sure it looks like a valid orderby statement
291
		if ( isset( $attr['orderby'] ) ) {
292
			$attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
293
			if ( !$attr['orderby'] )
294
				unset( $attr['orderby'] );
295
		}
296
297
		extract( shortcode_atts( array(
0 ignored issues
show
Bug introduced by
shortcode_atts(array('or...lse), $attr, 'gallery') cannot be passed to extract() as the parameter $var_array expects a reference.
Loading history...
298
			'order'     => 'ASC',
299
			'orderby'   => 'menu_order ID',
300
			'id'        => $post->ID,
301
			'include'   => '',
302
			'exclude'   => '',
303
			'slideshow' => false
304
		), $attr, 'gallery' ) );
305
306
		// Custom image size and always use it
307
		add_image_size( 'win8app-column', 480 );
308
		$size = 'win8app-column';
309
310
		$id = intval( $id );
311
		if ( 'RAND' === $order )
312
			$orderby = 'none';
313
314
		if ( !empty( $include ) ) {
315
			$include      = preg_replace( '/[^0-9,]+/', '', $include );
316
			$_attachments = get_posts( array( 'include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby ) );
317
			$attachments  = array();
318
			foreach ( $_attachments as $key => $val ) {
319
				$attachments[$val->ID] = $_attachments[$key];
320
			}
321
		} elseif ( !empty( $exclude ) ) {
322
			$exclude     = preg_replace( '/[^0-9,]+/', '', $exclude );
323
			$attachments = get_children( array( 'post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby ) );
324
		} else {
325
			$attachments = get_children( array( 'post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby ) );
326
		}
327
328
		if ( ! empty( $attachments ) ) {
329
			foreach ( $attachments as $id => $attachment ) {
330
				$link = isset( $attr['link'] ) && 'file' === $attr['link'] ? wp_get_attachment_link( $id, $size, false, false ) : wp_get_attachment_link( $id, $size, true, false );
331
332
				if ( $captiontag && trim($attachment->post_excerpt) ) {
333
					$output .= "<div class='wp-caption aligncenter'>$link
334
						<p class='wp-caption-text'>" . wptexturize($attachment->post_excerpt) . "</p>
335
						</div>";
336
				} else {
337
					$output .= $link . ' ';
338
				}
339
			}
340
		}
341
	}
342
}
343