Completed
Push — master ( 71e3f4...1ed264 )
by Marin
02:34
created

Term_Meta_Container::save()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
c 3
b 1
f 0
dl 0
loc 10
rs 9.4285
cc 2
eloc 6
nc 2
nop 1
1
<?php
2
3
namespace Carbon_Fields\Container;
4
5
use Carbon_Fields\Datastore\Meta_Datastore;
6
use Carbon_Fields\Datastore\Term_Meta_Datastore;
7
use Carbon_Fields\Exception\Incorrect_Syntax_Exception;
8
9
/**
10
 * Term meta container class. 
11
 */
12
class Term_Meta_Container extends Container {
13
	protected $term_id;
14
15
	public $settings = array(
16
		'taxonomy' => array( 'category' ),
17
		'show_on_level' => false,
18
	);
19
20
	/**
21
	 * Create a new term meta fields container
22
	 *
23
	 * @param string $title Unique title of the container
24
	 **/
25
	public function __construct( $title ) {
26
		parent::__construct( $title );
27
28
		if ( ! $this->get_datastore() ) {
29
			$this->set_datastore( new Term_Meta_Datastore() );
30
		}
31
	}
32
33
	/**
34
	 * Assign DataStore instance for use by the container fields
35
	 *
36
	 * @param object $store
37
	 **/
38
	public function set_datastore( Meta_Datastore $store ) {
39
		parent::set_datastore( $store );
40
	}
41
42
	/**
43
	 * Bind attach() and save() to the appropriate WordPress actions.
44
	 **/
45
	public function init() {
46
		// force taxonomy to be array
47
		if ( ! is_array( $this->settings['taxonomy'] ) ) {
48
			$this->settings['taxonomy'] = array( $this->settings['taxonomy'] );
49
		}
50
51
		add_action( 'admin_init', array( $this, '_attach' ) );
52
53 View Code Duplication
		foreach ( $this->settings['taxonomy'] as $taxonomy ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
54
			add_action( 'edited_' . $taxonomy, array( $this, '_save' ), 10, 2 );
55
			add_action( 'created_' . $taxonomy, array( $this, '_save' ), 10, 2 );
56
		}
57
	}
58
59
	/**
60
	 * Perform save operation after successful is_valid_save() check.
61
	 * The call is propagated to all fields in the container.
62
	 *
63
	 * @param int $term_id ID of the term against which save() is ran
64
	 **/
65
	public function save( $term_id ) {
66
		$this->set_term_id( $term_id );
67
68
		foreach ( $this->fields as $field ) {
69
			$field->set_value_from_input();
70
			$field->save();
71
		}
72
73
		do_action( 'carbon_after_save_term_meta', $term_id );
74
	}
75
76
	/**
77
	 * Perform checks whether the container should be attached during the current request
78
	 *
79
	 * @return bool True if the container is allowed to be attached
80
	 **/
81
	public function is_valid_attach() {
82
		if ( isset( $_GET['taxonomy'] ) && in_array( $_GET['taxonomy'], $this->settings['taxonomy'] ) ) {
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_GET
Loading history...
83
			return true;
84
		}
85
86
		return false;
87
	}
88
89
	/**
90
	 * Perform checks whether the current save() request is valid.
91
	 *
92
	 * @param int $term_id ID of the term against which save() is ran
93
	 * @return bool
94
	 **/
95
	public function is_valid_save( $term_id = null ) {
96
		if ( ! isset( $_REQUEST[ $this->get_nonce_name() ] ) || ! wp_verify_nonce( $_REQUEST[ $this->get_nonce_name() ], $this->get_nonce_name() ) ) { // Input var okay.
0 ignored issues
show
introduced by
Detected usage of a non-sanitized input variable: $_REQUEST
Loading history...
97
			return false;
98
		} else if ( $term_id < 1 ) {
99
			return false;
100
		}
101
102
		return true;
103
	}
104
105
	/**
106
	 * Add term meta for each of the container taxonomies
107
	 **/
108
	public function attach() {
109
		foreach ( $this->settings['taxonomy'] as $taxonomy ) {
110
			add_action( $taxonomy . '_edit_form_fields', array( $this, 'render' ), 10, 2 );
111
			add_action( $taxonomy . '_add_form_fields', array( $this, 'render' ), 10, 2 );
112
		}
113
	}
114
	
115
	/**
116
	 * Revert the result of attach()
117
	 *
118
	 **/
119
	public function detach() {
120
		parent::detach();
121
122
		remove_action( 'admin_init', array( $this, '_attach' ) );
123
124 View Code Duplication
		foreach ( $this->settings['taxonomy'] as $taxonomy ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
125
			remove_action( 'edited_' . $taxonomy, array( $this, '_save' ), 10, 2 );
126
			remove_action( 'created_' . $taxonomy, array( $this, '_save' ), 10, 2 );
127
		}
128
129
		// unregister field names
130
		foreach ( $this->fields as $field ) {
131
			$this->drop_unique_field_name( $field->get_name() );
132
		}
133
	}
134
135
	/**
136
	 * Output the container markup
137
	 **/
138
	public function render( $term = null ) {
139
		if ( is_object( $term ) ) {
140
			$this->set_term_id( $term->term_id );
141
		}
142
143
		include \Carbon_Fields\DIR . '/templates/Container/term_meta.php';
144
	}
145
146
	/**
147
	 * Set the term ID the container will operate with.
148
	 *
149
	 * @param int $term_id
150
	 **/
151
	public function set_term_id( $term_id ) {
152
		$this->term_id = $term_id;
153
		$this->store->set_id( $term_id );
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Carbon_Fields\Datastore\Datastore_Interface as the method set_id() does only exist in the following implementations of said interface: Carbon_Fields\Datastore\Comment_Meta_Datastore, Carbon_Fields\Datastore\Meta_Datastore, Carbon_Fields\Datastore\Nav_Menu_Datastore, Carbon_Fields\Datastore\Post_Meta_Datastore, Carbon_Fields\Datastore\Term_Meta_Datastore, Carbon_Fields\Datastore\User_Meta_Datastore.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
154
	}
155
156
157
	/**
158
	 * Perform checks whether there is a field registered with the name $name.
159
	 * If not, the field name is recorded.
160
	 *
161
	 * @param string $name
162
	 **/
163 View Code Duplication
	public function verify_unique_field_name( $name ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
164
		if ( empty( $this->settings['taxonomy'] ) ) {
165
			Incorrect_Syntax_Exception::raise( 'Panel instance is not setup correctly (missing taxonomy)' );
166
		}
167
168
		foreach ( $this->settings['taxonomy'] as $taxonomy ) {
169
			if ( ! isset( self::$registered_field_names[ $taxonomy ] ) ) {
170
				self::$registered_field_names[ $taxonomy ] = array();
171
			}
172
173
			if ( in_array( $name, self::$registered_field_names[ $taxonomy ] ) ) {
174
				Incorrect_Syntax_Exception::raise( 'Field name "' . $name . '" already registered' );
175
			}
176
177
			self::$registered_field_names[ $taxonomy ][] = $name;
178
		}
179
	}
180
181
	/**
182
	 * Remove field name $name from the list of unique field names
183
	 *
184
	 * @param string $name
185
	 **/
186 View Code Duplication
	public function drop_unique_field_name( $name ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
187
		foreach ( $this->settings['taxonomy'] as $taxonomy ) {
188
			$index = array_search( $name, self::$registered_field_names[ $taxonomy ] );
189
			if ( $index !== false ) {
190
				unset( self::$registered_field_names[ $taxonomy ][ $index ] );
191
			}
192
		}
193
	}
194
195
	/**
196
	 * Show the container only on terms from the specified taxonomies.
197
	 *
198
	 * @param string|array $taxonomies
199
	 * @return object $this
200
	 **/
201
	public function show_on_taxonomy( $taxonomies ) {
202
		$taxonomies = (array) $taxonomies;
203
204
		$this->settings['taxonomy'] = $taxonomies;
205
206
		return $this;
207
	}
208
209
	/** 
210
	 * Show the container only on particular term level. 
211
	 *
212
	 * @param int $term_level 
213
	 * @return object $this 
214
	 */ 
215
	public function show_on_level( $term_level ) {                    
216
		$this->settings['show_on_level'] = $term_level; 
217
		return $this; 
218
	} 
219
220
}
221