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

ShallowDuplicating::import()   B

Complexity

Conditions 8
Paths 13

Size

Total Lines 56
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 31
nc 13
nop 1
dl 0
loc 56
rs 7.3333
c 0
b 0
f 0

How to fix   Long Method   

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\Terms;
4
5
use lloc\Msls\ContentImport\Importers\BaseImporter;
6
use lloc\Msls\MslsOptionsTax;
7
use lloc\Msls\MslsOptionsTaxTerm;
8
9
/**
10
 * Class ShallowDuplicating
11
 *
12
 * Duplicates, if needed, the terms assigned to the post without recursion for hierarchical taxonomies.
13
 *
14
 * @package lloc\Msls\ContentImport\Importers\Terms
15
 */
16
class ShallowDuplicating extends BaseImporter {
17
18
	const TYPE = 'shallow-duplicating';
19
20
	/**
21
	 * @var array
22
	 */
23
	protected $reset_taxonomies = [];
24
25
	/**
26
	 * Returns an array of information about the importer.
27
	 *
28
	 * @return \stdClass
29
	 */
30
	public static function info() {
31
		return (object) [
32
			'slug'        => static::TYPE,
33
			'name'        => __( 'Shallow Duplicating', 'multisite-language-switcher' ),
34
			'description' => __( 'Shallow (one level deep) duplication or assignment of the source post taxonomy terms to the destnation post.', 'multisite-language-switcher' )
35
		];
36
	}
37
38
	public function import( array $data ) {
39
		$source_blog_id = $this->import_coordinates->source_blog_id;
40
		$source_post_id = $this->import_coordinates->source_post_id;
41
		$dest_post_id   = $this->import_coordinates->dest_post_id;
42
		$dest_lang      = $this->import_coordinates->dest_lang;
43
44
		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...
45
46
		$source_terms     = wp_get_post_terms( $source_post_id, get_taxonomies() );
47
		$source_terms_ids = wp_list_pluck( $source_terms, 'term_id' );
48
		$msls_terms       = array_combine(
49
			$source_terms_ids,
50
			array_map( array( MslsOptionsTaxTerm::class, 'create' ), $source_terms_ids )
51
		);
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
		/** @var \WP_Term $term */
56
		foreach ( $source_terms as $term ) {
57
			// is there a translation for the term in this blog?
58
			$msls_term    = $msls_terms[ $term->term_id ];
59
			$dest_term_id = $msls_term->{$dest_lang};
60
61
			if ( null === $dest_term_id ) {
62
				$dest_term_id = $this->create_local_term( $term, $msls_term, $dest_lang );
63
			}
64
65
			if ( false === $dest_term_id ) {
66
				continue;
67
			}
68
69
			$added = $this->update_object_terms( $dest_post_id, $dest_term_id, $term->taxonomy );
70
71
			if ( is_array( $added ) && ! count( array_filter( $added ) ) ) {
72
				// while we think the term translation exists it might not, let's create it
73
				$dest_term_id = $this->create_local_term( $term, $msls_term, $dest_lang );
74
75
				if ( false === $dest_term_id ) {
76
					continue;
77
				}
78
79
				// and try again
80
				$added = $this->update_object_terms( $dest_post_id, $dest_term_id, $term->taxonomy );
81
			}
82
83
			if ( $added instanceof \WP_Error ) {
0 ignored issues
show
Bug introduced by
The class WP_Error 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...
84
				$this->logger->log_error( "term/added/{$term->taxonomy}", array( $term->name => $term->term_id ) );
85
			} else {
86
				$this->logger->log_success( "term/added/{$term->taxonomy}", array( $term->name => $term->term_id ) );
87
			}
88
		}
89
90
		restore_current_blog();
91
92
		return $data;
93
	}
94
95
	protected function create_local_term( \WP_Term $term, MslsOptionsTax $msls_term, $dest_lang ) {
96
		$meta         = get_term_meta( $term->term_id );
97
		$dest_term_id = wp_create_term( $term->name, $term->taxonomy );
98
99
		if ( $dest_term_id instanceof \WP_Error ) {
0 ignored issues
show
Bug introduced by
The class WP_Error 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...
100
			$this->logger->log_error( "term/created/{$term->taxonomy}", [ $term->name ] );
101
102
			return false;
103
		}
104
105
		$dest_term_id = (int) reset( $dest_term_id );
106
		$this->relations->should_create( $msls_term, $dest_lang, $dest_term_id );
107
		$this->logger->log_success( "term/created/{$term->taxonomy}", [ $term->name => $term->term_id ] );
108
		$meta = $this->filter_term_meta( $meta, $term );
109
		if ( ! empty( $meta ) ) {
110
			foreach ( $meta as $key => $value ) {
111
				add_term_meta( $dest_term_id, $key, $value );
112
			}
113
		}
114
115
		return $dest_term_id;
116
	}
117
118
	protected function filter_term_meta( array $meta, \WP_Term $term ) {
119
		/**
120
		 * Filters the list of term meta that should not be imported for a term.
121
		 *
122
		 * @param array $blacklist
123
		 * @param \WP_Term $term
124
		 * @param array $meta
125
		 * @param ImportCoordinates $import_coordinates
126
		 */
127
		$blacklist = apply_filters( 'msls_content_import_term_meta_blacklist', array(), $term, $meta, $this->import_coordinates );
128
129
		return array_diff_key( $meta, array_combine( $blacklist, $blacklist ) );
130
	}
131
132
	protected function update_object_terms( $object_id, $dest_term_id, $taxonomy ) {
133
		if ( ! in_array( $taxonomy, $this->reset_taxonomies, true ) ) {
134
			wp_set_object_terms( $object_id, [], $taxonomy );
135
			$this->reset_taxonomies[] = $taxonomy;
136
		}
137
138
		return wp_add_object_terms( $object_id, $dest_term_id, $taxonomy );
139
	}
140
}
141