SaasApiToken.php
108 lines
| 1 | <?php |
| 2 | /** |
| 3 | * Base Modal class. |
| 4 | * php version 5.6 |
| 5 | * |
| 6 | * @category Model |
| 7 | * @package SureTriggers |
| 8 | * @author BSF <username@example.com> |
| 9 | * @license https://www.gnu.org/licenses/gpl-3.0.html GPLv3 |
| 10 | * @link https://www.brainstormforce.com/ |
| 11 | * @since 1.0.0 |
| 12 | */ |
| 13 | |
| 14 | namespace SureTriggers\Models; |
| 15 | |
| 16 | use SureTriggers\Support\Encryption; |
| 17 | use SureTriggers\Controllers\OptionController; |
| 18 | |
| 19 | /** |
| 20 | * The API token model. |
| 21 | */ |
| 22 | class SaasApiToken { |
| 23 | |
| 24 | /** |
| 25 | * The option key. |
| 26 | * |
| 27 | * @var string |
| 28 | */ |
| 29 | protected $key = 'secret_key'; |
| 30 | |
| 31 | /** |
| 32 | * Prevent php warnings. |
| 33 | */ |
| 34 | final public function __construct() {} |
| 35 | |
| 36 | /** |
| 37 | * Save and encrypt the API token. |
| 38 | * |
| 39 | * @param string|null $value The API token. |
| 40 | * @return void|null|string |
| 41 | */ |
| 42 | protected function save( $value ) { |
| 43 | if ( null === $value || empty( $value ) ) { |
| 44 | return OptionController::set_option( $this->key, $value ); |
| 45 | } else { |
| 46 | if ( strlen( $value ) > 80 ) { |
| 47 | return $value; |
| 48 | } |
| 49 | return OptionController::set_option( $this->key, Encryption::encrypt( $value ) ); |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | /** |
| 54 | * Get and decrypt the API token |
| 55 | * |
| 56 | * @return mixed|string The decoded API token. |
| 57 | */ |
| 58 | protected function get() { |
| 59 | $plain_token = OptionController::get_option( $this->key ); |
| 60 | $token = Encryption::decrypt( $plain_token ); |
| 61 | if ( ! $token ) { |
| 62 | if ( is_string( $plain_token ) && ! empty( $plain_token ) ) { |
| 63 | self::save( $plain_token ); |
| 64 | $token = $plain_token; |
| 65 | } else { |
| 66 | $token = null; |
| 67 | } |
| 68 | } |
| 69 | return $token; |
| 70 | } |
| 71 | |
| 72 | /** |
| 73 | * Forward call to method |
| 74 | * |
| 75 | * @param array|string $method Method to call. |
| 76 | * @param array|mixed $params Method params. |
| 77 | * |
| 78 | * @return mixed Mixed value. |
| 79 | */ |
| 80 | public function __call( $method, $params ) { |
| 81 | /** |
| 82 | * |
| 83 | * Ignore line |
| 84 | * |
| 85 | * @phpstan-ignore-next-line |
| 86 | */ |
| 87 | return call_user_func_array( [ $this, $method ], $params ); |
| 88 | } |
| 89 | |
| 90 | /** |
| 91 | * Static Facade Accessor |
| 92 | * |
| 93 | * @param array|string $method Method to call. |
| 94 | * @param array|mixed $params Method params. |
| 95 | * |
| 96 | * @return mixed Mixed value. |
| 97 | */ |
| 98 | public static function __callStatic( $method, $params ) { |
| 99 | /** |
| 100 | * |
| 101 | * Ignore line |
| 102 | * |
| 103 | * @phpstan-ignore-next-line |
| 104 | */ |
| 105 | return call_user_func_array( [ new static(), $method ], $params ); |
| 106 | } |
| 107 | } |
| 108 |