| 1 |
<?php |
| 2 |
|
| 3 |
namespace Payplug\PayplugWoocommerce\Gateway; |
| 4 |
|
| 5 |
// Exit if accessed directly |
| 6 |
if ( ! defined( 'ABSPATH' ) ) { |
| 7 |
exit; |
| 8 |
} |
| 9 |
|
| 10 |
use Payplug\Authentication; |
| 11 |
use Payplug\Exception\PayplugException; |
| 12 |
|
| 13 |
class PayplugPermissions { |
| 14 |
|
| 15 |
const OPTION_NAME = 'payplug_permission'; |
| 16 |
const LIVE_MODE = 'use_live_mode'; |
| 17 |
const SAVE_CARD = 'can_save_cards'; |
| 18 |
|
| 19 |
/** |
| 20 |
* @var PayplugGateway |
| 21 |
*/ |
| 22 |
private $gateway; |
| 23 |
|
| 24 |
/** |
| 25 |
* The current mode for the gateway. |
| 26 |
* |
| 27 |
* @var string |
| 28 |
*/ |
| 29 |
private $gateway_mode; |
| 30 |
|
| 31 |
/** |
| 32 |
* @var array |
| 33 |
*/ |
| 34 |
private $permissions; |
| 35 |
|
| 36 |
/** |
| 37 |
* PayplugPermissions constructor. |
| 38 |
* |
| 39 |
* @param PayplugGateway $gateway |
| 40 |
*/ |
| 41 |
public function __construct( PayplugGateway $gateway ) { |
| 42 |
$this->gateway = $gateway; |
| 43 |
$this->gateway_mode = $gateway->get_current_mode(); |
| 44 |
$this->load_permissions(); |
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* Get all permissions. |
| 49 |
* |
| 50 |
* @return array |
| 51 |
*/ |
| 52 |
public function get_permissions() { |
| 53 |
return $this->permissions; |
| 54 |
} |
| 55 |
|
| 56 |
/** |
| 57 |
* Check if user has specific permission. |
| 58 |
* |
| 59 |
* @param string $user_can |
| 60 |
* |
| 61 |
* @return bool |
| 62 |
*/ |
| 63 |
public function has_permissions( $user_can ) { |
| 64 |
if ( empty( $user_can ) ) { |
| 65 |
return false; |
| 66 |
} |
| 67 |
|
| 68 |
return isset( $this->permissions[ $user_can ] ) && true === $this->permissions[ $user_can ]; |
| 69 |
} |
| 70 |
|
| 71 |
/** |
| 72 |
* Delete permissions for the current mode. |
| 73 |
* |
| 74 |
* @return bool |
| 75 |
*/ |
| 76 |
public function clear_permissions() { |
| 77 |
return delete_transient( $this->get_key() ); |
| 78 |
} |
| 79 |
|
| 80 |
/** |
| 81 |
* Load permissions for the current mode. |
| 82 |
*/ |
| 83 |
protected function load_permissions() { |
| 84 |
|
| 85 |
$payplug_permissions = get_transient( $this->get_key() ); |
| 86 |
if ( ! empty( $payplug_permissions ) ) { |
| 87 |
$this->permissions = $payplug_permissions; |
| 88 |
|
| 89 |
return true; |
| 90 |
} |
| 91 |
|
| 92 |
try { |
| 93 |
$response = Authentication::getPermissions(); |
| 94 |
$this->permissions = ! empty( $response ) ? $response : []; |
| 95 |
set_transient( $this->get_key(), $this->permissions, DAY_IN_SECONDS ); |
| 96 |
|
| 97 |
return true; |
| 98 |
} catch ( PayplugException $e ) { |
| 99 |
$this->permissions = []; |
| 100 |
} |
| 101 |
|
| 102 |
return false; |
| 103 |
} |
| 104 |
|
| 105 |
/** |
| 106 |
* Build the key to retrieve the permissions. |
| 107 |
* |
| 108 |
* @return string |
| 109 |
*/ |
| 110 |
protected function get_key() { |
| 111 |
return self::OPTION_NAME . '_' . $this->gateway_mode; |
| 112 |
} |
| 113 |
} |
| 114 |
|