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

User_Meta_Container::set_user_id()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 3
Bugs 1 Features 0
Metric Value
c 3
b 1
f 0
dl 0
loc 4
rs 10
ccs 0
cts 4
cp 0
cc 1
eloc 3
nc 1
nop 1
crap 2
1
<?php
2
3
namespace Carbon_Fields\Container;
4
5
use Carbon_Fields\Datastore\Meta_Datastore;
6
use Carbon_Fields\Datastore\User_Meta_Datastore;
7
8
class User_Meta_Container extends Container {
9
	protected $user_id;
10
11
	public $settings = array(
12
		'show_on' => array(
13
			'role' => array()
14
		)
15
	);
16
17
	/**
18
	 * Create a new user meta container
19
	 *
20
	 * @param string $title Unique title of the container
21
	 **/
22 1
	public function __construct( $title ) {
23 1
		parent::__construct( $title );
24
25
		if ( ! $this->get_datastore() ) {
26
			$this->set_datastore( new User_Meta_Datastore() );
27
		}
28
	}
29
30
	/**
31
	 * Assign DataStore instance for use by the container fields
32
	 *
33
	 * @param object $store
34
	 **/
35
	public function set_datastore( Meta_Datastore $store ) {
36
		parent::set_datastore( $store );
37
	}
38
39
	/**
40
	 * Bind attach() and save() to the appropriate WordPress actions.
41
	 **/
42
	public function init() {
43
		add_action( 'admin_init', array( $this, '_attach' ) );
44
		add_action( 'profile_update', array( $this, '_save' ), 10, 1 );
45
		add_action( 'user_register', array( $this, '_save' ), 10, 1 );
46
	}
47
48
	/**
49
	 * Perform save operation after successful is_valid_save() check.
50
	 * The call is propagated to all fields in the container.
51
	 *
52
	 * @param int $user_id ID of the user against which save() is ran
53
	 **/
54 View Code Duplication
	public function save( $user_id ) {
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
		// Unhook action to garantee single save
56
		remove_action( 'profile_update', array( $this, '_save' ) );
57
58
		$this->set_user_id( $user_id );
59
60
		foreach ( $this->fields as $field ) {
61
			$field->set_value_from_input();
62
			$field->save();
63
		}
64
65
		do_action( 'carbon_after_save_user_meta', $user_id );
66
	}
67
68
	/**
69
	 * Checks whether the current request is valid
70
	 *
71
	 * @return bool
72
	 **/
73
	public function is_valid_save( $user_id = 0 ) {
74
		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...
75
			return false;
76
		} else if ( ! $this->is_valid_attach() ) {
77
			return false;
78
		}
79
80
		return $this->is_valid_save_conditions( $user_id );
81
	}
82
83
	/**
84
	 * Perform checks whether the current save() request is valid
85
	 *
86
	 * @param int $user_id ID of the user against which save() is ran
87
	 * @return bool
88
	 **/
89
	public function is_valid_save_conditions( $user_id ) {
90
		$valid = true;
91
		$user = get_userdata( $user_id );
92
93
		if ( empty( $user->roles ) ) {
94
			return;
95
		}
96
97
		// Check user role
98
		if ( ! empty( $this->settings['show_on']['role'] ) ) {
99
			$allowed_roles = (array) $this->settings['show_on']['role'];
100
101
			// array_shift removed the returned role from the $user_profile->roles
102
			// $roles_to_shift prevents changing of the $user_profile->roles variable
103
			$roles_to_shift = $user->roles;
104
			$profile_role = array_shift( $roles_to_shift );
105
			if ( ! in_array( $profile_role, $allowed_roles ) ) {
106
				$valid = false;
107
			}
108
		}
109
110
		return $valid;
111
	}
112
113
	/**
114
	 * Show the container only on users who have the $role role.
115
	 *
116
	 * @param string $role
117
	 * @return object $this
118
	 **/
119
	public function show_on_user_role( $role ) {
120
		$this->settings['show_on']['role'] = (array) $role;
121
122
		return $this;
123
	}
124
125
	/**
126
	 * Add the container to the user
127
	 **/
128
	public function attach() {
129
		add_action( 'show_user_profile', array( $this, 'render' ), 10, 1 );
130
		add_action( 'edit_user_profile', array( $this, 'render' ), 10, 1 );
131
		add_action( 'user_new_form', array( $this, 'render' ), 10, 1 );
132
	}
133
134
	/**
135
	 * Whether we're on the user profile page
136
	 **/
137
	public function is_profile_page() {
138
		global $pagenow;
139
140
		return $pagenow === 'profile.php' || $pagenow === 'user-new.php' || $pagenow === 'user-edit.php';
141
	}
142
143
	/**
144
	 * Perform checks whether the container should be attached during the current request
145
	 *
146
	 * @return bool True if the container is allowed to be attached
147
	 **/
148
	public function is_valid_attach() {
149
		if ( ! current_user_can( 'edit_users' ) || ! $this->is_profile_page() ) {
150
			return false;
151
		}
152
153
		return true;
154
	}
155
156
	/**
157
	 * Output the container markup
158
	 **/
159
	public function render( $user_profile = null ) {
160
		$profile_role = '';
161
162
		if ( is_object( $user_profile ) ) {
163
			$this->set_user_id( $user_profile->ID );
164
165
			// array_shift removed the returned role from the $user_profile->roles
166
			// $roles_to_shift prevents changing of the $user_profile->roles variable
167
			$roles_to_shift = $user_profile->roles;
168
			$profile_role = array_shift( $roles_to_shift );
169
		}
170
171
		include \Carbon_Fields\DIR . '/templates/Container/user_meta.php';
172
	}
173
174
	/**
175
	 * Set the user ID the container will operate with.
176
	 *
177
	 * @param int $user_id
178
	 **/
179
	public function set_user_id( $user_id ) {
180
		$this->user_id = $user_id;
181
		$this->store->set_id( $user_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...
182
	}
183
}
184