Completed
Push — master ( 326b37...e590c5 )
by Marin
02:43
created

Term_Meta_Container::is_valid_attach()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
c 3
b 1
f 0
dl 0
loc 7
rs 9.4285
cc 3
eloc 4
nc 2
nop 0
1
<?php
2
3
namespace Carbon_Fields\Container;
4
5
use Carbon_Fields\Datastore\Term_Meta_Datastore;
6
use Carbon_Fields\Exception\Incorrect_Syntax_Exception;
7
8
/**
9
 * Term meta container class. 
10
 */
11
class Term_Meta_Container extends Container {
12
	protected $term_id;
13
14
	public $settings = array(
15
		'taxonomy' => array( 'category' ),
16
		'show_on_level' => false,
17
	);
18
19
	/**
20
	 * Create a new term meta fields container
21
	 *
22
	 * @param string $title Unique title of the container
23
	 **/
24
	public function __construct( $title ) {
25
		parent::__construct( $title );
26
27
		if ( ! $this->get_datastore() ) {
28
			$this->set_datastore( new Term_Meta_Datastore() );
29
		}
30
	}
31
32
	/**
33
	 * Bind attach() and save() to the appropriate WordPress actions.
34
	 **/
35
	public function init() {
36
		// force taxonomy to be array
37
		if ( ! is_array( $this->settings['taxonomy'] ) ) {
38
			$this->settings['taxonomy'] = array( $this->settings['taxonomy'] );
39
		}
40
41
		add_action( 'admin_init', array( $this, '_attach' ) );
42
43 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...
44
			add_action( 'edited_' . $taxonomy, array( $this, '_save' ), 10, 2 );
45
			add_action( 'created_' . $taxonomy, array( $this, '_save' ), 10, 2 );
46
		}
47
	}
48
49
	/**
50
	 * Perform save operation after successful is_valid_save() check.
51
	 * The call is propagated to all fields in the container.
52
	 *
53
	 * @param int $term_id ID of the term against which save() is ran
54
	 **/
55
	public function save( $term_id ) {
56
		$this->set_term_id( $term_id );
57
58
		foreach ( $this->fields as $field ) {
59
			$field->set_value_from_input();
60
			$field->save();
61
		}
62
63
		do_action( 'carbon_after_save_term_meta', $term_id );
64
	}
65
66
	/**
67
	 * Perform checks whether the container should be attached during the current request
68
	 *
69
	 * @return bool True if the container is allowed to be attached
70
	 **/
71
	public function is_valid_attach() {
72
		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...
73
			return true;
74
		}
75
76
		return false;
77
	}
78
79
	/**
80
	 * Perform checks whether the current save() request is valid.
81
	 *
82
	 * @param int $term_id ID of the term against which save() is ran
83
	 * @return bool
84
	 **/
85
	public function is_valid_save( $term_id = null ) {
86
		if ( ! isset( $_REQUEST[ $this->get_nonce_name() ] ) || ! wp_verify_nonce( $_REQUEST[ $this->get_nonce_name() ], $this->get_nonce_name() ) ) {
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_REQUEST
Loading history...
87
			return false;
88
		} else if ( $term_id < 1 ) {
89
			return false;
90
		}
91
92
		return true;
93
	}
94
95
	/**
96
	 * Add term meta for each of the container taxonomies
97
	 **/
98
	public function attach() {
99
		foreach ( $this->settings['taxonomy'] as $taxonomy ) {
100
			add_action( $taxonomy . '_edit_form_fields', array( $this, 'render' ), 10, 2 );
101
			add_action( $taxonomy . '_add_form_fields', array( $this, 'render' ), 10, 2 );
102
		}
103
	}
104
	
105
	/**
106
	 * Revert the result of attach()
107
	 *
108
	 **/
109
	public function detach() {
110
		parent::detach();
111
112
		remove_action( 'admin_init', array( $this, '_attach' ) );
113
114 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...
115
			remove_action( 'edited_' . $taxonomy, array( $this, '_save' ), 10, 2 );
116
			remove_action( 'created_' . $taxonomy, array( $this, '_save' ), 10, 2 );
117
		}
118
119
		// unregister field names
120
		foreach ( $this->fields as $field ) {
121
			$this->drop_unique_field_name( $field->get_name() );
122
		}
123
	}
124
125
	/**
126
	 * Output the container markup
127
	 **/
128
	public function render( $term = null ) {
129
		if ( is_object( $term ) ) {
130
			$this->set_term_id( $term->term_id );
131
		}
132
133
		include \Carbon_Fields\DIR . '/templates/Container/term_meta.php';
134
	}
135
136
	/**
137
	 * Set the term ID the container will operate with.
138
	 *
139
	 * @param int $term_id
140
	 **/
141
	public function set_term_id( $term_id ) {
142
		$this->term_id = $term_id;
143
		$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\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...
144
	}
145
146
147
	/**
148
	 * Perform checks whether there is a field registered with the name $name.
149
	 * If not, the field name is recorded.
150
	 *
151
	 * @param string $name
152
	 **/
153 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...
154
		if ( empty( $this->settings['taxonomy'] ) ) {
155
			Incorrect_Syntax_Exception::raise( 'Panel instance is not setup correctly (missing taxonomy)' );
156
		}
157
158
		foreach ( $this->settings['taxonomy'] as $taxonomy ) {
159
			if ( ! isset( self::$registered_field_names[ $taxonomy ] ) ) {
160
				self::$registered_field_names[ $taxonomy ] = array();
161
			}
162
163
			if ( in_array( $name, self::$registered_field_names[ $taxonomy ] ) ) {
164
				Incorrect_Syntax_Exception::raise( 'Field name "' . $name . '" already registered' );
165
			}
166
167
			self::$registered_field_names[ $taxonomy ][] = $name;
168
		}
169
	}
170
171
	/**
172
	 * Remove field name $name from the list of unique field names
173
	 *
174
	 * @param string $name
175
	 **/
176 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...
177
		foreach ( $this->settings['taxonomy'] as $taxonomy ) {
178
			$index = array_search( $name, self::$registered_field_names[ $taxonomy ] );
179
			if ( $index !== false ) {
180
				unset( self::$registered_field_names[ $taxonomy ][ $index ] );
181
			}
182
		}
183
	}
184
185
	/**
186
	 * Show the container only on terms from the specified taxonomies.
187
	 *
188
	 * @param string|array $taxonomies
189
	 * @return object $this
190
	 **/
191
	public function show_on_taxonomy( $taxonomies ) {
192
		$taxonomies = (array) $taxonomies;
193
194
		$this->settings['taxonomy'] = $taxonomies;
195
196
		return $this;
197
	}
198
199
	/** 
200
	 * Show the container only on particular term level. 
201
	 *
202
	 * @param int $term_level 
203
	 * @return object $this 
204
	 */ 
205
	public function show_on_level( $term_level ) {                    
206
		$this->settings['show_on_level'] = $term_level; 
207
		return $this; 
208
	} 
209
210
}
211