| 1 |
<?php |
| 2 |
/** |
| 3 |
* @package Polylang |
| 4 |
*/ |
| 5 |
|
| 6 |
namespace WP_Syntex\Polylang\Capabilities; |
| 7 |
|
| 8 |
use WP_User; |
| 9 |
use WP_Syntex\Polylang\Capabilities\User\Creator; |
| 10 |
use WP_Syntex\Polylang\Capabilities\User\User_Interface; |
| 11 |
use WP_Syntex\Polylang\Capabilities\User\Creator_Interface; |
| 12 |
|
| 13 |
/** |
| 14 |
* A class allowing to map Polylang's custom user capabilities to WP's native ones. |
| 15 |
* |
| 16 |
* @since 3.8 |
| 17 |
*/ |
| 18 |
class Capabilities { |
| 19 |
public const LANGUAGES = 'manage_languages'; |
| 20 |
public const TRANSLATIONS = 'manage_translations'; |
| 21 |
|
| 22 |
/** |
| 23 |
* The user creator to be used for capability checks. |
| 24 |
* |
| 25 |
* @var Creator_Interface|null |
| 26 |
*/ |
| 27 |
private static ?Creator_Interface $creator = null; |
| 28 |
|
| 29 |
/** |
| 30 |
* Constructor. |
| 31 |
* |
| 32 |
* @since 3.8 |
| 33 |
*/ |
| 34 |
public function __construct() { |
| 35 |
add_filter( 'map_meta_cap', array( $this, 'map_custom_caps' ), 1, 2 ); |
| 36 |
} |
| 37 |
|
| 38 |
/** |
| 39 |
* Filters user capabilities to handle PLL's custom capabilities. |
| 40 |
* |
| 41 |
* @since 3.8 |
| 42 |
* |
| 43 |
* @param string[] $caps Primitive capabilities required by the user. |
| 44 |
* @param string $cap Capability being checked. |
| 45 |
* @return string[] |
| 46 |
*/ |
| 47 |
public function map_custom_caps( $caps, $cap ) { |
| 48 |
if ( in_array( $cap, array( self::TRANSLATIONS, self::LANGUAGES ), true ) ) { |
| 49 |
$caps = array_diff( $caps, array( $cap ) ); |
| 50 |
$caps[] = 'manage_options'; |
| 51 |
} |
| 52 |
|
| 53 |
return $caps; |
| 54 |
} |
| 55 |
|
| 56 |
/** |
| 57 |
* Returns the user instance to be used for capability checks. |
| 58 |
* |
| 59 |
* @since 3.8 |
| 60 |
* |
| 61 |
* @param WP_User|null $user The user to decorate. If null, the current user is used. |
| 62 |
* @return User_Interface The user instance. |
| 63 |
*/ |
| 64 |
public static function get_user( ?WP_User $user = null ): User_Interface { |
| 65 |
if ( ! self::$creator ) { |
| 66 |
self::$creator = new Creator(); |
| 67 |
} |
| 68 |
|
| 69 |
return self::$creator->get( $user ?? wp_get_current_user() ); |
| 70 |
} |
| 71 |
|
| 72 |
/** |
| 73 |
* Sets the user creator to be used for capability checks. |
| 74 |
* |
| 75 |
* Having a separate class to create the decorated user allows for better decoupling. |
| 76 |
* This allows to set a creator object without dependence to a `WP_User`. |
| 77 |
* |
| 78 |
* @since 3.8 |
| 79 |
* |
| 80 |
* @param Creator_Interface $creator The user creator to be used for capability checks. |
| 81 |
* @return void |
| 82 |
*/ |
| 83 |
public static function set_user_creator( Creator_Interface $creator ): void { |
| 84 |
self::$creator = $creator; |
| 85 |
} |
| 86 |
} |
| 87 |
|