| 1 |
<?php |
| 2 |
/** |
| 3 |
* OpenStation App Framework — standalone Auth adapter. |
| 4 |
* |
| 5 |
* An in-memory principal: the host hands over a user id and the |
| 6 |
* capabilities it holds. `'*'` grants everything, which is what a |
| 7 |
* CLI runner or a test wants. |
| 8 |
* |
| 9 |
* @package OpenStation |
| 10 |
*/ |
| 11 |
|
| 12 |
namespace OpenStation\App\Standalone; |
| 13 |
|
| 14 |
use OpenStation\App\Contracts\Auth as AuthContract; |
| 15 |
|
| 16 |
// Direct access, unless a standalone host is booting on bare PHP. |
| 17 |
if ( ! defined( 'ABSPATH' ) ) { |
| 18 |
defined( 'OPENSTATION_STANDALONE' ) || exit; |
| 19 |
} |
| 20 |
|
| 21 |
/** |
| 22 |
* In-memory principal. |
| 23 |
*/ |
| 24 |
final class Auth implements AuthContract { |
| 25 |
|
| 26 |
/** |
| 27 |
* Acting user id. |
| 28 |
* |
| 29 |
* @var int |
| 30 |
*/ |
| 31 |
private $user_id; |
| 32 |
|
| 33 |
/** |
| 34 |
* Granted capabilities. |
| 35 |
* |
| 36 |
* @var string[] |
| 37 |
*/ |
| 38 |
private $capabilities; |
| 39 |
|
| 40 |
/** |
| 41 |
* @param int $user_id Acting user id; 0 for anonymous. |
| 42 |
* @param string[] $capabilities Capabilities held, or `array( '*' )` for all. |
| 43 |
*/ |
| 44 |
public function __construct( $user_id = 0, array $capabilities = array() ) { |
| 45 |
$this->user_id = (int) $user_id; |
| 46 |
$this->capabilities = array_map( 'strval', $capabilities ); |
| 47 |
} |
| 48 |
|
| 49 |
/** {@inheritDoc} */ |
| 50 |
public function user_id() { |
| 51 |
return $this->user_id; |
| 52 |
} |
| 53 |
|
| 54 |
/** {@inheritDoc} */ |
| 55 |
public function is_logged_in() { |
| 56 |
return $this->user_id > 0; |
| 57 |
} |
| 58 |
|
| 59 |
/** {@inheritDoc} */ |
| 60 |
public function can( $capability, ...$args ) { |
| 61 |
return in_array( '*', $this->capabilities, true ) |
| 62 |
|| in_array( (string) $capability, $this->capabilities, true ); |
| 63 |
} |
| 64 |
} |
| 65 |
|