Completed
Push — add/feature-rollout ( 16c199...2484fa )
by
unknown
10:53
created

Jetpack_Custom_CSS_Data_Migration   A

Complexity

Total Complexity 31

Size/Duplication

Total Lines 221
Duplicated Lines 19.91 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
dl 44
loc 221
rs 9.8
c 0
b 0
f 0
wmc 31
lcom 1
cbo 3

6 Methods

Rating   Name   Duplication   Size   Complexity  
A add_hooks() 0 9 2
D do_migration() 0 84 14
A register_legacy_post_type() 0 22 2
B get_post() 33 33 5
A get_all_revisions() 5 15 2
B get_options() 0 19 6

How to fix   Duplicated Code   

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:

1
<?php
2
/**
3
 * Migration from Jetpack Custom CSS to WordPress' Core CSS.
4
 *
5
 * @since 4.4.2
6
 *
7
 * @package Jetpack
8
 */
9
10
/**
11
 * Class Jetpack_Custom_CSS_Data_Migration
12
 */
13
class Jetpack_Custom_CSS_Data_Migration {
14
	/**
15
	 * Set up assorted actions and filters used by this class.
16
	 */
17
	public static function add_hooks() {
18
		add_action( 'init', array( __CLASS__, 'register_legacy_post_type' ) );
19
		add_action( 'admin_init', array( __CLASS__, 'do_migration' ) );
20
21
		include_once( dirname( __FILE__ ) . '/custom-css.php' );
22
		if ( ! is_admin() ) {
23
			add_action( 'init', array( 'Jetpack_Custom_CSS', 'init' ) );
24
		}
25
	}
26
27
	/**
28
	 * Do the bulk of the migration.
29
	 *
30
	 * @return int|null
31
	 */
32
	public static function do_migration() {
33
		Jetpack_Options::update_option( 'custom_css_4.7_migration', true );
34
		Jetpack::log( 'custom_css_4.7_migration', 'start' );
35
36
		if ( ! post_type_exists( 'safecss' ) ) {
37
			self::register_legacy_post_type();
38
		}
39
40
		/** This filter is documented in modules/custom-css/custom-css.php */
41
		$preprocessors      = apply_filters( 'jetpack_custom_css_preprocessors', array() );
42
		$core_css_post      = wp_get_custom_css_post();
43
		$jetpack_css_post   = self::get_post();
44
		$revisions          = self::get_all_revisions();
45
46
		// Migrate the settings from revision meta to theme mod.
47
		$options = self::get_options( $jetpack_css_post->ID );
48
		set_theme_mod( 'jetpack_custom_css', $options );
49
50
		if ( empty( $revisions ) || ! is_array( $revisions ) ) {
51
			if ( $jetpack_css_post instanceof WP_Post ) {
0 ignored issues
show
Bug introduced by
The class WP_Post does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
52
				// Feed in the raw, if the current setting is Sass/LESS, it'll filter it inside.
53
				wp_update_custom_css_post( $jetpack_css_post->post_content );
54
				return 1;
55
			}
56
			return null;
57
		}
58
59
		$revisions            = array_reverse( $revisions );
60
		$themes               = Jetpack_Custom_CSS_Enhancements::get_themes();
61
		$migrated             = array();
62
63
		foreach ( $revisions as $post_id => $post ) {
64
			// Jetpack had stored the theme Name, not the stylesheet directory, for ... reasons.
65
			// Get the stylesheet.  If null, the theme is no longer available.  Skip.
66
			$stylesheet = isset( $themes[ $post->post_excerpt ] ) ? $themes[ $post->post_excerpt ] : null;
67
			if ( empty( $stylesheet ) ) {
68
				continue;
69
			}
70
71
			$migrated[] = $post->ID;
72
			$preprocessor = get_post_meta( $post->ID, 'custom_css_preprocessor', true );
73
			$css = $post->post_content;
74
			$pre = '';
75
76
			// Do a revision by revision parsing.
77
			if ( $preprocessor && isset( $preprocessors[ $preprocessor ] ) ) {
78
				$pre = $css;
79
				$css = call_user_func( $preprocessors[ $preprocessor ]['callback'], $pre );
80
			}
81
82
			// Do we need to remove any filters here for users without `unfiltered_html` ?
83
			wp_update_custom_css_post( $css, array(
84
				'stylesheet'   => $stylesheet,
85
				'preprocessed' => $pre,
86
			) );
87
		}
88
89
		// If we've migrated some CSS for the current theme and there was already something there in the Core dataset ...
90
		if ( $core_css_post && $jetpack_css_post ) {
91
			$preprocessor = $options['preprocessor'];
92
93
			$css = $core_css_post->post_content;
94
			$pre = $core_css_post->post_content_filtered;
95
			if ( $preprocessor ) {
96
				if ( $pre ) {
97
					$pre .= "\r\n\r\n/*\r\n\t" . esc_js( __( 'CSS Migrated from Jetpack:', 'jetpack' ) ) . "\r\n*/\r\n\r\n";
98
				}
99
				$pre .= $jetpack_css_post->post_content;
100
101
				$css .= "\r\n\r\n/*\r\n\t" . esc_js( __( 'CSS Migrated from Jetpack:', 'jetpack' ) ) . "\r\n*/\r\n\r\n";
102
				$css .= call_user_func( $preprocessors[ $preprocessor ]['callback'], $jetpack_css_post->post_content );
103
			} else {
104
				$css .= "\r\n\r\n/*\r\n\t" . esc_js( __( 'CSS Migrated from Jetpack:', 'jetpack' ) ) . "\r\n*/\r\n\r\n";
105
				$css .= $jetpack_css_post->post_content;
106
			}
107
108
			wp_update_custom_css_post( $css, array(
109
				'preprocessed' => $pre,
110
			) );
111
		}
112
113
		Jetpack::log( 'custom_css_4.7_migration', count( $migrated ) . 'revisions migrated' );
114
		return count( $migrated );
115
	}
116
117
	/**
118
	 * Re-register the legacy CPT so we can play with the content already in the database.
119
	 */
120
	public static function register_legacy_post_type() {
121
		if ( post_type_exists( 'safecss' ) ) {
122
			return;
123
		}
124
		// Register safecss as a custom post_type
125
		// Explicit capability definitions are largely unnecessary because the posts are manipulated in code via an options page, managing CSS revisions does check the capabilities, so let's ensure that the proper caps are checked.
126
		register_post_type( 'safecss', array(
127
			'label'        => 'Custom CSS',
128
			'supports'     => array( 'revisions' ),
129
			'can_export'   => false,
130
			'rewrite'      => false,
131
			'capabilities' => array(
132
				'edit_post'          => 'edit_theme_options',
133
				'read_post'          => 'read',
134
				'delete_post'        => 'edit_theme_options',
135
				'edit_posts'         => 'edit_theme_options',
136
				'edit_others_posts'  => 'edit_theme_options',
137
				'publish_posts'      => 'edit_theme_options',
138
				'read_private_posts' => 'read',
139
			),
140
		) );
141
	}
142
143
	/**
144
	 * Get the post used for legacy storage.
145
	 *
146
	 * Jetpack used to use a single post for all themes, just blanking it on theme switch.  This gets that post.
147
	 *
148
	 * @return array|bool|null|WP_Post
149
	 */
150 View Code Duplication
	public static function get_post() {
151
		/** This filter is documented in modules/custom-css/custom-css.php */
152
		$custom_css_post_id = apply_filters( 'jetpack_custom_css_pre_post_id', null );
153
		if ( ! is_null( $custom_css_post_id ) ) {
154
			return get_post( $custom_css_post_id );
155
		}
156
157
		$custom_css_post_id = wp_cache_get( 'custom_css_post_id' );
158
159
		if ( false === $custom_css_post_id ) {
160
			$custom_css_posts = get_posts( array(
161
				'posts_per_page' => 1,
162
				'post_type'      => 'safecss',
163
				'post_status'    => 'publish',
164
				'orderby'        => 'date',
165
				'order'          => 'DESC',
166
			) );
167
168
			$custom_css_post_id = 0;
169
			if ( count( $custom_css_posts ) > 0 ) {
170
				$custom_css_post_id = $custom_css_posts[0]->ID;
171
			}
172
173
			// Save post_id=0 to note that no safecss post exists.
174
			wp_cache_set( 'custom_css_post_id', $custom_css_post_id );
175
		}
176
177
		if ( ! $custom_css_post_id ) {
178
			return false;
179
		}
180
181
		return get_post( $custom_css_post_id );
182
	}
183
184
	/**
185
	 * Get all revisions of the Jetpack CSS CPT entry.
186
	 *
187
	 * @return array
188
	 */
189
	public static function get_all_revisions() {
190
		$post = self::get_post();
191
192
		if ( ! $post ) {
193
			return array();
194
		}
195
196
		$revisions = wp_get_post_revisions( $post->ID, array(
197
			'posts_per_page' => -1,
198
			'orderby'        => 'date',
199
			'order'          => 'DESC',
200
		) );
201
202
		return $revisions;
203
	}
204
205
	/**
206
	 * Get the options stored for a given revision ID.
207
	 *
208
	 * Jetpack used to version the settings by storing them as meta on the revision.
209
	 *
210
	 * @param integer $post_id Post ID.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $post_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
211
	 *
212
	 * @return array
213
	 */
214
	public static function get_options( $post_id = null ) {
215
		if ( empty( $post_id ) ) {
216
			$post = self::get_post();
217
			$post_id = $post->ID;
218
		}
219
220
		$meta = get_post_meta( $post_id );
221
222
		$replace = false;
223
		if ( isset( $meta['custom_css_add'][0] ) && 'no' === $meta['custom_css_add'][0] ) {
224
			$replace = true;
225
		}
226
227
		return array(
228
			'preprocessor'  => isset( $meta['custom_css_preprocessor'][0] ) ? $meta['custom_css_preprocessor'][0] : '',
229
			'replace'       => $replace,
230
			'content_width' => isset( $meta['content_width'][0] )           ? $meta['content_width'][0]           : '',
231
		);
232
	}
233
}
234
235
Jetpack_Custom_CSS_Data_Migration::add_hooks();
236