AdminCapabilityGiver::add_cap_to_admin()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 8
ccs 0
cts 5
cp 0
crap 6
rs 10
1
<?php namespace EmailLog\Core;
2
3
use EmailLog\Core\UI\Page\LogListPage;
4
5
defined( 'ABSPATH' ) || exit; // Exit if accessed directly.
6
7
/**
8
 * Gives capability to admin.
9
 * By default admins should be able to manage email logs.
10
 *
11
 * @since 2.1.0
12
 */
13
class AdminCapabilityGiver implements Loadie {
14
15
	public function load() {
16
		add_filter( 'user_has_cap', array( $this, 'add_cap_to_admin_cap_list' ), 10, 4 );
17
	}
18
19
	/**
20
	 * Add `manage_email_logs` capability to admin's list of capabilities during `user_has_cap` check.
21
	 *
22
	 * In new installs this capability will be added to admins on plugin install.
23
	 * But in old installs the admins will not have this capability and that's why we need to add it using the filter.
24
	 *
25
	 * @param array    $allcaps An array of all the user's capabilities.
26
	 * @param array    $caps    Actual capabilities for meta capability.
27
	 * @param array    $args    Optional parameters passed to has_cap(), typically object ID.
28
	 * @param \WP_User $user    The user object.
29
	 *
30
	 * @return array Modified list of user's capabilities.
31
	 */
32
	public function add_cap_to_admin_cap_list( $allcaps, $caps, $args, $user ) {
33
		if ( ! in_array( 'administrator', $user->roles ) ) {
34
			return $allcaps;
35
		}
36
37
		if ( array_key_exists( LogListPage::CAPABILITY, $allcaps ) ) {
38
			return $allcaps;
39
		}
40
41
		$allcaps[ LogListPage::CAPABILITY ] = true;
42
43
		return $allcaps;
44
	}
45
46
	/**
47
	 * Add Manage Email Logs capability to administrator role.
48
	 * This will be called on install.
49
	 */
50
	public function add_cap_to_admin() {
51
		$admin = get_role( 'administrator' );
52
53
		if ( is_null( $admin ) ) {
54
			return;
55
		}
56
57
		$admin->add_cap( LogListPage::CAPABILITY );
58
	}
59
}
60