Completed
Push — add/packages-role ( 37648c )
by Marin
33:06 queued 24:49
created

Roles::translate_role_to_cap()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * A user roles class for Jetpack.
4
 *
5
 * @package jetpack-roles
6
 */
7
8
namespace Automattic\Jetpack;
9
10
/**
11
 * Class Automattic\Jetpack\Roles
12
 *
13
 * Contains utilities for translating user roles to capabilities and vice versa.
14
 */
15
class Roles {
16
	/**
17
	 * Map of roles we care about, and their corresponding minimum capabilities.
18
	 *
19
	 * @access protected
20
	 * @static
21
	 *
22
	 * @var array
23
	 */
24
	protected static $capability_translations = array(
25
		'administrator' => 'manage_options',
26
		'editor'        => 'edit_others_posts',
27
		'author'        => 'publish_posts',
28
		'contributor'   => 'edit_posts',
29
		'subscriber'    => 'read',
30
	);
31
32
	/**
33
	 * Get the role of the current user.
34
	 *
35
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
36
	 */
37 View Code Duplication
	public static function translate_current_user_to_role() {
38
		foreach ( self::$capability_translations as $role => $cap ) {
39
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
40
				return $role;
41
			}
42
		}
43
44
		return false;
45
	}
46
47
	/**
48
	 * Get the role of a particular user.
49
	 *
50
	 * @param \WP_User $user User object.
51
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
52
	 */
53 View Code Duplication
	public static function translate_user_to_role( $user ) {
54
		foreach ( self::$capability_translations as $role => $cap ) {
55
			if ( user_can( $user, $role ) || user_can( $user, $cap ) ) {
56
				return $role;
57
			}
58
		}
59
60
		return false;
61
	}
62
63
	/**
64
	 * Get the minimum capability for a role.
65
	 *
66
	 * @param string $role Role name.
67
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
68
	 */
69
	public static function translate_role_to_cap( $role ) {
70
		if ( ! isset( self::$capability_translations[ $role ] ) ) {
71
			return false;
72
		}
73
74
		return self::$capability_translations[ $role ];
75
	}
76
}
77