class-abstract-capability-manager.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /**
  3. * WPSEO plugin file.
  4. *
  5. * @package WPSEO\Admin\Capabilities
  6. */
  7. /**
  8. * Abstract Capability Manager shared code.
  9. */
  10. abstract class WPSEO_Abstract_Capability_Manager implements WPSEO_Capability_Manager {
  11. /**
  12. * Registered capabilities.
  13. *
  14. * @var array
  15. */
  16. protected $capabilities = [];
  17. /**
  18. * Registers a capability.
  19. *
  20. * @param string $capability Capability to register.
  21. * @param array $roles Roles to add the capability to.
  22. * @param bool $overwrite Optional. Use add or overwrite as registration method.
  23. */
  24. public function register( $capability, array $roles, $overwrite = false ) {
  25. if ( $overwrite || ! isset( $this->capabilities[ $capability ] ) ) {
  26. $this->capabilities[ $capability ] = $roles;
  27. return;
  28. }
  29. // Combine configurations.
  30. $this->capabilities[ $capability ] = array_merge( $roles, $this->capabilities[ $capability ] );
  31. // Remove doubles.
  32. $this->capabilities[ $capability ] = array_unique( $this->capabilities[ $capability ] );
  33. }
  34. /**
  35. * Returns the list of registered capabilitities.
  36. *
  37. * @return string[] Registered capabilities.
  38. */
  39. public function get_capabilities() {
  40. return array_keys( $this->capabilities );
  41. }
  42. /**
  43. * Returns a list of WP_Role roles.
  44. *
  45. * The string array of role names are converted to actual WP_Role objects.
  46. * These are needed to be able to use the API on them.
  47. *
  48. * @param array $roles Roles to retrieve the objects for.
  49. *
  50. * @return WP_Role[] List of WP_Role objects.
  51. */
  52. protected function get_wp_roles( array $roles ) {
  53. $wp_roles = array_map( 'get_role', $roles );
  54. return array_filter( $wp_roles );
  55. }
  56. /**
  57. * Filter capability roles.
  58. *
  59. * @param string $capability Capability to filter roles for.
  60. * @param array $roles List of roles which can be filtered.
  61. *
  62. * @return array Filtered list of roles for the capability.
  63. */
  64. protected function filter_roles( $capability, array $roles ) {
  65. /**
  66. * Filter: Allow changing roles that a capability is added to.
  67. *
  68. * @api array $roles The default roles to be filtered.
  69. */
  70. $filtered = apply_filters( $capability . '_roles', $roles );
  71. // Make sure we have the expected type.
  72. if ( ! is_array( $filtered ) ) {
  73. return [];
  74. }
  75. return $filtered;
  76. }
  77. }