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

Comment_Meta_Container::verify_unique_field_name()   A

Complexity

Conditions 3
Paths 4

Size

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