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

Comment_Meta_Container::set_datastore()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Carbon_Fields\Container;
4
5
use Carbon_Fields\Datastore\Meta_Datastore;
6
use Carbon_Fields\Datastore\Comment_Meta_Datastore;
7
use Carbon_Fields\Exception\Incorrect_Syntax_Exception;
8
9
/**
10
 * Comment meta container class. 
11
 */
12
class Comment_Meta_Container extends Container {
13
	protected $comment_id;
14
15
	/**
16
	 * Create a new comment meta container
17
	 *
18
	 * @param string $title Unique title of the container
19
	 **/
20
	public function __construct( $title ) {
21
		parent::__construct( $title );
22
23
		if ( ! $this->get_datastore() ) {
24
			$this->set_datastore( new Comment_Meta_Datastore() );
25
		}
26
	}
27
28
	/**
29
	 * Assign DataStore instance for use by the container fields
30
	 *
31
	 * @param object $store
32
	 **/
33
	public function set_datastore( Meta_Datastore $store ) {
34
		parent::set_datastore( $store );
35
	}
36
37
	/**
38
	 * Perform instance initialization after calling setup()
39
	 **/
40
	public function init() {
41
		if ( isset( $_GET['c'] ) && $comment_id = absint( $_GET['c'] ) ) { // Input var okay.
42
			$this->set_comment_id( $comment_id );
43
		}
44
45
		add_action( 'admin_init', array( $this, '_attach' ) );
46
		add_action( 'edit_comment', array( $this, '_save' ) );
47
	}
48
49
	/**
50
	 * Checks whether the current request is valid
51
	 *
52
	 * @return bool
53
	 **/
54 View Code Duplication
	public function is_valid_save() {
1 ignored issue
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...
55
		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...
56
			return false;
57
		} 
58
59
		return true;
60
	}
61
62
	/**
63
	 * Add meta box to the comment
64
	 **/
65
	public function attach() {
66
		add_meta_box(
67
			$this->id, 
68
			$this->title, 
69
			array( $this, 'render' ), 
70
			'comment', 
71
			'normal',
72
			'high'
73
		);
74
	}
75
	
76
	/**
77
	 * Revert the result of attach()
78
	 **/
79 View Code Duplication
	public function detach() {
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...
80
		parent::detach();
81
82
		remove_action( 'admin_init', array( $this, '_attach' ) );
83
		remove_action( 'edit_comment', array( $this, '_save' ) );
84
85
		// unregister field names
86
		foreach ( $this->fields as $field ) {
87
			$this->drop_unique_field_name( $field->get_name() );
88
		}
89
	}
90
91
	/**
92
	 * Output the container markup
93
	 **/
94
	public function render() {
95
		include \Carbon_Fields\DIR . '/templates/Container/comment_meta.php';
96
	}
97
98
	/**
99
	 * Set the comment ID the container will operate with.
100
	 *
101
	 * @param int $comment_id
102
	 **/
103
	public function set_comment_id( $comment_id ) {
104
		$this->comment_id = $comment_id;
105
		$this->store->set_id( $comment_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...
106
	}
107
108
	/**
109
	 * Perform save operation after successful is_valid_save() check.
110
	 * The call is propagated to all fields in the container.
111
	 *
112
	 * @param int $comment_id ID of the comment against which save() is ran
113
	 **/
114
	public function save( $comment_id ) {
115
116
		// Unhook action to guarantee single save
117
		remove_action( 'edit_comment', array( $this, '_save' ) );
118
119
		$this->set_comment_id( $comment_id );
120
121
		foreach ( $this->fields as $field ) {
122
			$field->set_value_from_input();
123
			$field->save();
124
		}
125
	}
126
127
	/**
128
	 * Perform checks whether there is a field registered with the name $name.
129
	 * If not, the field name is recorded.
130
	 *
131
	 * @param string $name
132
	 **/
133
	public function verify_unique_field_name( $name ) {
134
		if ( ! isset( self::$registered_field_names['comment'] ) ) {
135
			self::$registered_field_names['comment'] = array();
136
		}
137
138
		if ( in_array( $name, self::$registered_field_names['comment'] ) ) {
139
			throw new Incorrect_Syntax_Exception( 'Field name "' . $name . '" already registered' );
140
		}
141
142
		self::$registered_field_names['comment'][] = $name;
143
	}
144
145
	/**
146
	 * Remove field name $name from the list of unique field names
147
	 *
148
	 * @param string $name
149
	 **/
150
	public function drop_unique_field_name( $name ) {		
151
		$index = array_search( $name, self::$registered_field_names['comment'] );
152
		if ( $index !== false ) {
153
			unset( self::$registered_field_names['comment'][ $index ] );
154
		}
155
	}
156
157
}