PluginProbe
Metricool – Social media and site statistics / trunk
Metricool – Social media and site statistics vtrunk
2.1.0 2.0.2 2.0.1 2.0.0 1.27 trunk
metricool / app / Services / CapabilityService.php

CapabilityService.php in Metricool – Social media and site statistics trunk, at app/Services/CapabilityService.php

61 lines 1.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Metricool\Services;
6
7 class CapabilityService
8 {
9 /**
10 * The default WordPress roles that are suitable for the custom
11 * Metricool capabilities.
12 */
13 protected array $defaultCapabilityRoles = [
14 'administrator'
15 ];
16
17 /**
18 * Add a user capability to WordPress and add to administrator role
19 * @uses apply_filters metricool_add_manage_capability
20 */
21 public function addSiteCapability(string $capability, bool $handleSubsites = true, array $roles = []): void
22 {
23 $rolesToAddCapabilityTo = ($roles ?: $this->defaultCapabilityRoles);
24
25 /**
26 * Filter: metricool_suitable_custom_capability_roles
27 * @param array $rolesToAddCapabilityTo
28 * @return array
29 */
30 $rolesToAddCapabilityTo = apply_filters('metricool_suitable_custom_capability_roles', $rolesToAddCapabilityTo);
31
32 foreach ($rolesToAddCapabilityTo as $roleName) {
33 $role = get_role($roleName);
34 if ($role && !$role->has_cap($capability)) {
35 $role->add_cap($capability);
36 }
37 }
38
39 // Refresh the current user's cached capabilities so the new cap is
40 // available in the same request (e.g. for admin_menu checks).
41 wp_get_current_user()->get_role_caps();
42
43 if ($handleSubsites && is_multisite()) {
44 $this->addCapabilityToSubsites($capability);
45 }
46 }
47
48 /**
49 * Recursively add a capability to all subsites
50 */
51 private function addCapabilityToSubsites(string $capability): void
52 {
53 $sites = get_sites();
54 foreach ($sites as $site) {
55 switch_to_blog((int) $site->blog_id);
56 $this->addSiteCapability($capability, false);
57 restore_current_blog();
58 }
59 }
60 }
61