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

User_Meta_Container::init()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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