Completed
Pull Request — master (#111)
by Luca
02:07
created

Linking::import()   C

Complexity

Conditions 10
Paths 16

Size

Total Lines 89
Code Lines 53

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 53
nc 16
nop 1
dl 0
loc 89
rs 5.1943
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace lloc\Msls\ContentImport\Importers\PostThumbnail;
4
5
use lloc\Msls\ContentImport\AttachmentPathFinder;
6
use lloc\Msls\ContentImport\Importers\BaseImporter;
7
8
/**
9
 * Class Linking
10
 *
11
 * Creates an attachment post for the post thumbnail in the destination blog without duplicating the attachment files.
12
 *
13
 * @package lloc\Msls\ContentImport\Importers\PostThumbnail
14
 */
15
class Linking extends BaseImporter {
16
17
	const TYPE = 'linking';
18
19
	/**
20
	 * Returns an array of information about the importer.
21
	 *
22
	 * @return \stdClass
23
	 */
24
	public static function info() {
25
		return (object) [
26
			'slug'        => static::TYPE,
27
			'name'        => __( 'Linking', 'multisite-language-switcher' ),
28
			'description' => __( 'Links the featured image from the source post to the destination post; the image is not duplicated.', 'multisite-language-switcher' )
29
		];
30
	}
31
32
	public function import( array $data ) {
33
		$source_blog_id = $this->import_coordinates->source_blog_id;
34
		$source_post_id = $this->import_coordinates->source_post_id;
35
		$dest_post_id   = $this->import_coordinates->dest_post_id;
36
37
		switch_to_blog( $source_blog_id );
0 ignored issues
show
introduced by
switch_to_blog is not something you should ever need to do in a VIP theme context. Instead use an API (XML-RPC, REST) to interact with other sites if needed.
Loading history...
38
39
		$source_post_thumbnail_id         = (int) get_post_thumbnail_id( $source_post_id );
40
		$source_post_thumbnail_attachment = get_post( $source_post_thumbnail_id );
41
		$source_post_thumbnail_meta       = $source_post_thumbnail_attachment 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...
42
			$this->get_attachment_meta( $source_post_thumbnail_id )
43
			: false;
44
45
		if ( false === $source_post_thumbnail_meta ) {
46
			$this->logger->log_success( 'post-thumbnail/missing-meta', $source_post_thumbnail_id );
47
48
			return $data;
49
		}
50
51
		$source_upload_dir                = wp_upload_dir();
52
53
		switch_to_blog( $this->import_coordinates->dest_blog_id );
0 ignored issues
show
introduced by
switch_to_blog is not something you should ever need to do in a VIP theme context. Instead use an API (XML-RPC, REST) to interact with other sites if needed.
Loading history...
54
55
		if ( $source_post_thumbnail_attachment 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...
56
			// in some instances the folder sep. `/` might be duplicated, we de-duplicate it
57
			array_walk( $source_upload_dir, function ( &$entry ) {
58
				$entry = str_replace( '//', '/', $entry );
59
			} );
60
			$source_uploads_dir         = untrailingslashit( str_replace( $source_upload_dir['subdir'], '', $source_upload_dir['path'] ) );
61
			$source_post_thumbnail_file = $source_uploads_dir . '/' . $source_post_thumbnail_meta['_wp_attached_file'];
62
63
			// Check the type of file. We'll use this as the 'post_mime_type'.
64
			$filetype = wp_check_filetype( basename( $source_post_thumbnail_file ), null );
65
66
			// Prepare an array of post data for the attachment.
67
			$attachment = array(
68
				'guid'           => $source_post_thumbnail_attachment->guid,
69
				'post_mime_type' => $filetype['type'],
70
				'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $source_post_thumbnail_file ) ),
71
				'post_content'   => '',
72
				'post_status'    => 'inherit',
73
			);
74
75
			$existing_criteria = [
76
				'post_type'   => 'attachment',
77
				'title'       => $attachment['post_title'],
78
			];
79
80
			$found             = get_posts( $existing_criteria );
81
82
			if ( $found && $found[0] 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...
83
				$dest_post_thumbnail_id = $found[0]->ID;
84
				$this->logger->log_success( 'post-thumbnail/existing', $dest_post_thumbnail_id );
85
			} else {
86
				// Insert the attachment.
87
				$dest_post_thumbnail_id = wp_insert_attachment( $attachment, $source_post_thumbnail_file, $dest_post_id );
88
89
				if ( empty( $dest_post_thumbnail_id ) ) {
90
					$this->logger->log_error( 'post-thumbnail/created', $dest_post_thumbnail_id );
91
				} else {
92
					$this->logger->log_success( 'post-thumbnail/created', $dest_post_thumbnail_id );
93
				}
94
95
				// the `_wp_attached_file` meta has been set before, so we skip it
96
				unset( $source_post_thumbnail_meta['_wp_attached_file'] );
97
98
				foreach ( $source_post_thumbnail_meta as $key => $value ) {
99
					add_post_meta( $dest_post_thumbnail_id, $key, $value, true );
100
				}
101
			}
102
103
			update_post_meta( $dest_post_thumbnail_id, AttachmentPathFinder::LINKED, [
104
				'blog' => $source_blog_id,
105
				'post' => $source_post_thumbnail_id
106
			] );
107
108
			$dest_post_thumbnail_set = set_post_thumbnail( $dest_post_id, $dest_post_thumbnail_id );
109
110
			if ( $dest_post_thumbnail_set || $found ) {
111
				$this->logger->log_success( 'post-thumbnail/set', $dest_post_thumbnail_id );
112
			} else {
113
				$this->logger->log_error( 'post-thumbnail/set', $dest_post_thumbnail_id );
114
			}
115
		}
116
117
		restore_current_blog();
118
119
		return $data;
120
	}
121
122
	protected function get_attachment_meta( $source_post_thumbnail_id ) {
123
		$keys = [ '_wp_attached_file', '_wp_attachment_metadata', '_wp_attachment_image_alt' ];
124
125
		return array_combine( $keys, array_map( function ( $key ) use ( $source_post_thumbnail_id ) {
126
			return get_post_meta( $source_post_thumbnail_id, $key, true );
127
		}, $keys ) );
128
	}
129
}